Merge pull request #23583 from colemanw/apiDisabledFields
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * form to process actions on the group aspect of Custom Data
20 */
21class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
22
23 /**
fe482240 24 * The id of the contact associated with this contribution.
6a488035
TO
25 *
26 * @var int
6a488035
TO
27 */
28 public $_contactID;
29
1f1740fe
DL
30
31 /**
fe482240 32 * The id of the contribution object that is created when the form is submitted.
1f1740fe
DL
33 *
34 * @var int
1f1740fe
DL
35 */
36 public $_contributionID;
37
423616fa
CW
38 public $submitOnce = TRUE;
39
356bfcaf 40 /**
41 * @param $form
42 * @param $params
43 * @param $contributionParams
44 * @param $pledgeID
45 * @param $contribution
46 * @param $isEmailReceipt
47 * @return mixed
48 */
49 public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
50 if ($pledgeID) {
51 //when user doing pledge payments.
52 //update the schedule when payment(s) are made
53 $amount = $params['amount'];
be2fb01f 54 $pledgePaymentParams = [];
356bfcaf 55 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
56 $scheduledAmount = CRM_Core_DAO::getFieldValue(
57 'CRM_Pledge_DAO_PledgePayment',
58 $paymentId,
59 'scheduled_amount',
60 'id'
61 );
62
63 $pledgePayment = ($amount >= $scheduledAmount) ? $scheduledAmount : $amount;
64 if ($pledgePayment > 0) {
be2fb01f 65 $pledgePaymentParams[] = [
356bfcaf 66 'id' => $paymentId,
67 'contribution_id' => $contribution->id,
68 'status_id' => $contribution->contribution_status_id,
69 'actual_amount' => $pledgePayment,
be2fb01f 70 ];
356bfcaf 71 $amount -= $pledgePayment;
72 }
73 }
74 if ($amount > 0 && count($pledgePaymentParams)) {
75 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount;
76 }
77 foreach ($pledgePaymentParams as $p) {
78 CRM_Pledge_BAO_PledgePayment::add($p);
79 }
80
81 //update pledge status according to the new payment statuses
82 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
83 return $form;
84 }
85 else {
86 //when user creating pledge record.
be2fb01f 87 $pledgeParams = [];
356bfcaf 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'];
24c1b3d8 96 if ($pledgeParams['frequency_unit'] === 'month') {
356bfcaf 97 $pledgeParams['frequency_day'] = intval(date("d"));
98 }
99 else {
100 $pledgeParams['frequency_day'] = 1;
101 }
102 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
de6c59ca 103 if (!empty($params['start_date'])) {
2cfe2cf4 104 $pledgeParams['frequency_day'] = intval(date("d", strtotime($params['start_date'])));
cbbbf0ef 105 $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime($params['start_date']));
356bfcaf 106 }
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'];
114
115 //inherit campaign from contirb page.
9c1bc317 116 $pledgeParams['campaign_id'] = $contributionParams['campaign_id'] ?? NULL;
356bfcaf 117
118 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
119
120 $form->_params['pledge_id'] = $pledge->id;
121
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'];
128
129 //scheduled amount will be same as installment_amount.
130 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
131
132 //get total pledge amount.
133 $pledgeParams['total_pledge_amount'] = $pledge->amount;
134
135 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
136 return $form;
137 }
138 return $form;
139 }
140 }
141
c8bde7ea 142 /**
fe482240 143 * Set the parameters to be passed to contribution create function.
c8bde7ea
EM
144 *
145 * @param array $params
100fef9d 146 * @param int $financialTypeID
ab8fe4ef 147 * @param array $paymentProcessorOutcome
148 * @param string $receiptDate
100fef9d 149 * @param int $recurringContributionID
c8bde7ea 150 *
c8bde7ea 151 * @return array
24c1b3d8 152 * @throws \CRM_Core_Exception
c8bde7ea 153 */
a13f3d8c 154 public static function getContributionParams(
0ede7391 155 $params, $financialTypeID,
f6261e9d 156 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
be2fb01f 157 $contributionParams = [
c8bde7ea 158 'financial_type_id' => $financialTypeID,
9126e134 159 'receive_date' => !empty($params['receive_date']) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
6b409353
CW
160 'tax_amount' => $params['tax_amount'] ?? NULL,
161 'amount_level' => $params['amount_level'] ?? NULL,
c8bde7ea
EM
162 'invoice_id' => $params['invoiceID'],
163 'currency' => $params['currencyID'],
cbbbf0ef 164 'is_pay_later' => $params['is_pay_later'] ?? 0,
c8bde7ea
EM
165 //configure cancel reason, cancel date and thankyou date
166 //from 'contribution' type profile if included
cbbbf0ef 167 'cancel_reason' => $params['cancel_reason'] ?? 0,
a1a2a83d
TO
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,
c8bde7ea 170 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
cbbbf0ef 171 'skipLineItem' => $params['skipLineItem'] ?? 0,
be2fb01f 172 ];
3febe800 173
a7a33651 174 if ($paymentProcessorOutcome) {
9c1bc317 175 $contributionParams['payment_processor'] = $paymentProcessorOutcome['payment_processor'] ?? NULL;
a7a33651 176 }
7127b69c 177 if (!empty($params["is_email_receipt"])) {
be2fb01f 178 $contributionParams += [
7127b69c 179 'receipt_date' => $receiptDate,
be2fb01f 180 ];
7127b69c 181 }
c8bde7ea 182
c8bde7ea
EM
183 if ($recurringContributionID) {
184 $contributionParams['contribution_recur_id'] = $recurringContributionID;
185 }
186
0ede7391 187 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
c8bde7ea
EM
188 if (isset($contributionParams['invoice_id'])) {
189 $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
190 'CRM_Contribute_DAO_Contribution',
191 $contributionParams['invoice_id'],
192 'id',
193 'invoice_id'
194 );
195 }
196
197 return $contributionParams;
198 }
199
fda99f2f
EM
200 /**
201 * Get non-deductible amount.
202 *
203 * This is a bit too much about wierd form interpretation to be this deep.
204 *
0e480632 205 * @see https://issues.civicrm.org/jira/browse/CRM-11885
fda99f2f
EM
206 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
207 * it.
ceb9fecb
EM
208 *
209 * @param array $params
210 * @param CRM_Financial_BAO_FinancialType $financialType
211 * @param bool $online
5afce5ad 212 * @param CRM_Contribute_Form_Contribution_Confirm $form
fda99f2f
EM
213 *
214 * @return array
215 */
8a594d37 216 public static function getNonDeductibleAmount($params, $financialType, $online, $form) {
fda99f2f
EM
217 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
218 return $params['non_deductible_amount'];
219 }
9c1bc317 220 $priceSetId = $params['priceSetId'] ?? NULL;
5afce5ad 221 // return non-deductible amount if it is set at the price field option level
05465712 222 if ($priceSetId && !empty($form->_lineItem)) {
223 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem);
224 }
225
226 if (!empty($nonDeductibleAmount)) {
227 return $nonDeductibleAmount;
5afce5ad 228 }
fda99f2f
EM
229 else {
230 if ($financialType->is_deductible) {
231 if ($online && isset($params['selectProduct'])) {
9c1bc317 232 $selectProduct = $params['selectProduct'] ?? NULL;
fda99f2f
EM
233 }
234 if (!$online && isset($params['product_name'][0])) {
235 $selectProduct = $params['product_name'][0];
236 }
237 // if there is a product - compare the value to the contribution amount
238 if (isset($selectProduct) &&
24c1b3d8 239 $selectProduct !== 'no_thanks'
fda99f2f
EM
240 ) {
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;
248 }
249 // product value does NOT exceed contribution amount
250 else {
251 return $productDAO->price;
252 }
253 }
254 // contribution is deductible - but there is no product
255 else {
256 return '0.00';
257 }
258 }
259 // contribution is NOT deductible
260 else {
261 return $params['amount'];
262 }
263 }
264 }
265
6a488035 266 /**
fe482240 267 * Set variables up before form is built.
6a488035
TO
268 */
269 public function preProcess() {
6a488035 270 parent::preProcess();
cde484fd 271
6a488035
TO
272 // lineItem isn't set until Register postProcess
273 $this->_lineItem = $this->get('lineItem');
58466af1 274 $this->_ccid = $this->get('ccid');
9a7ba24d 275
a9768188
EM
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']);
6a488035 281 }
6a488035 282
a9768188
EM
283 $this->_params['tax_amount'] = $this->get('tax_amount');
284 $this->_useForMember = $this->get('useForMember');
6a488035 285
2e09448c 286 CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($this->_params);
5df36634 287
358b59a5 288 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
6a488035 289
a9768188
EM
290 if (!empty($this->_membershipBlock)) {
291 $this->_params['selectMembership'] = $this->get('selectMembership');
292 }
9c86599c 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);
dd22a911 296
9c86599c 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);
2db8bc3f 300 }
6a488035
TO
301
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']) {
cbbbf0ef 305 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt'] ?? NULL);
6a488035
TO
306 }
307 // if onbehalf-of-organization
4779abb3 308 if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
f85a1a75 309 if (empty($this->_params['org_option']) && empty($this->_params['organization_id'])) {
9c1bc317 310 $this->_params['organization_id'] = $this->_params['onbehalfof_id'] ?? NULL;
f85a1a75 311 }
6a488035 312 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
be2fb01f 313 $addressBlocks = [
a13f3d8c
TO
314 'street_address',
315 'city',
316 'state_province',
317 'postal_code',
318 'country',
319 'supplemental_address_1',
320 'supplemental_address_2',
321 'supplemental_address_3',
322 'postal_code_suffix',
323 'geo_code_1',
324 'geo_code_2',
325 'address_name',
be2fb01f 326 ];
6a488035 327
be2fb01f 328 $blocks = ['email', 'phone', 'im', 'url', 'openid'];
6a488035
TO
329 foreach ($this->_params['onbehalf'] as $loc => $value) {
330 $field = $typeId = NULL;
331 if (strstr($loc, '-')) {
fb8d25da 332 [$field, $locType] = explode('-', $loc);
6a488035
TO
333 }
334
335 if (in_array($field, $addressBlocks)) {
24c1b3d8 336 if ($locType === 'Primary') {
6a488035
TO
337 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
338 $locType = $defaultLocationType->id;
cde484fd
DL
339 }
340
24c1b3d8 341 if ($field === 'country') {
6a488035
TO
342 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
343 }
24c1b3d8 344 elseif ($field === 'state_province') {
6a488035
TO
345 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
346 }
cde484fd 347
6a488035
TO
348 $isPrimary = 1;
349 if (isset($this->_params['onbehalf_location']['address'])
a13f3d8c
TO
350 && count($this->_params['onbehalf_location']['address']) > 0
351 ) {
6a488035
TO
352 $isPrimary = 0;
353 }
cde484fd 354
6a488035 355 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
a7488080 356 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
6a488035 357 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
a13f3d8c 358 }
6a488035
TO
359 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
360 }
361 elseif (in_array($field, $blocks)) {
362 if (!$typeId || is_numeric($typeId)) {
a13f3d8c
TO
363 $blockName = $fieldName = $field;
364 $locationType = 'location_type_id';
24c1b3d8 365 if ($locType === 'Primary') {
6a488035
TO
366 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
367 $locationValue = $defaultLocationType->id;
368 }
369 else {
370 $locationValue = $locType;
371 }
a13f3d8c 372 $locTypeId = '';
be2fb01f 373 $phoneExtField = [];
6a488035 374
fb8d25da 375 if ($field === 'url') {
a13f3d8c 376 $blockName = 'website';
887e764d 377 $locationType = 'website_type_id';
fb8d25da 378 [$field, $locationValue] = explode('-', $loc);
6a488035 379 }
fb8d25da 380 elseif ($field === 'im') {
6a488035
TO
381 $fieldName = 'name';
382 $locTypeId = 'provider_id';
a13f3d8c 383 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
6a488035
TO
384 }
385 elseif ($field == 'phone') {
fb8d25da 386 [$field, $locType, $typeId] = explode('-', $loc);
6a488035
TO
387 $locTypeId = 'phone_type_id';
388
389 //check if extension field exists
a13f3d8c 390 $extField = str_replace('phone', 'phone_ext', $loc);
6a488035 391 if (isset($this->_params['onbehalf'][$extField])) {
be2fb01f 392 $phoneExtField = ['phone_ext' => $this->_params['onbehalf'][$extField]];
6a488035
TO
393 }
394 }
395
396 $isPrimary = 1;
f1b56c48 397 if (isset($this->_params['onbehalf_location'][$blockName])
a13f3d8c
TO
398 && count($this->_params['onbehalf_location'][$blockName]) > 0
399 ) {
400 $isPrimary = 0;
6a488035
TO
401 }
402 if ($locationValue) {
be2fb01f 403 $blockValues = [
a13f3d8c 404 $fieldName => $value,
6a488035 405 $locationType => $locationValue,
a13f3d8c 406 'is_primary' => $isPrimary,
be2fb01f 407 ];
6a488035
TO
408
409 if ($locTypeId) {
be2fb01f 410 $blockValues = array_merge($blockValues, [$locTypeId => $typeId]);
6a488035
TO
411 }
412 if (!empty($phoneExtField)) {
413 $blockValues = array_merge($blockValues, $phoneExtField);
414 }
415
416 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
417 }
418 }
419 }
420 elseif (strstr($loc, 'custom')) {
421 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
422 $value = $this->_params['onbehalf']["{$loc}_id"];
423 }
424 $this->_params['onbehalf_location']["{$loc}"] = $value;
425 }
426 else {
24c1b3d8 427 if ($loc === 'contact_sub_type') {
6a488035
TO
428 $this->_params['onbehalf_location'][$loc] = $value;
429 }
430 else {
431 $this->_params['onbehalf_location'][$field] = $value;
432 }
433 }
434 }
435 }
a7488080 436 elseif (!empty($this->_values['is_for_organization'])) {
6a488035
TO
437 // no on behalf of an organization, CRM-5519
438 // so reset loc blocks from main params.
be2fb01f 439 foreach ([
1330f57a
SL
440 'phone',
441 'email',
442 'address',
443 ] as $blk) {
6a488035
TO
444 if (isset($this->_params[$blk])) {
445 unset($this->_params[$blk]);
446 }
447 }
448 }
90102a32 449 $this->setRecurringMembershipParams();
6a488035
TO
450
451 if ($this->_pcpId) {
452 $params = $this->processPcp($this, $this->_params);
453 $this->_params = $params;
454 }
455 $this->_params['invoiceID'] = $this->get('invoiceID');
456
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'];
460 }
461
569df8ec
DG
462 // assign contribution page id to the template so we can add css class for it
463 $this->assign('contributionPageID', $this->_id);
cbbbf0ef 464 $this->assign('is_for_organization', $this->_params['is_for_organization'] ?? NULL);
569df8ec 465
6a488035
TO
466 $this->set('params', $this->_params);
467 }
468
469 /**
fe482240 470 * Build the form object.
6a488035
TO
471 */
472 public function buildQuickForm() {
8684f612 473 // FIXME: Some of this code is identical to Thankyou.php and should be broken out into a shared function
6a488035
TO
474 $this->assignToTemplate();
475
476 $params = $this->_params;
6a488035 477 // make sure we have values for it
2f44fc96 478 if (!empty($this->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid)) {
a13f3d8c 479 $honorName = NULL;
133e2c99 480 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
481
133e2c99 482 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
4779abb3 483 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor']);
6a488035 484
be2fb01f 485 $fieldTypes = ['Contact'];
4779abb3 486 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($this->_values['honoree_profile_id']);
487 $this->buildCustom($this->_values['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
6a488035 488 }
2627f4ba 489 $this->assign('receiptFromEmail', $this->_values['receipt_from_email'] ?? NULL);
1bec3b51 490 $this->assign('amount_block_is_active', $this->isFormSupportsNonMembershipContributions());
6a488035 491
147b56dc
MW
492 // Make a copy of line items array to use for display only
493 $tplLineItems = $this->_lineItem;
97288cdc 494 if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
f1b56c48 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'
03b412ae
PB
498 $this->assign('totalTaxAmount', $params['tax_amount']);
499 }
f1b56c48 500 $this->assignLineItemsToTemplate($tplLineItems);
501
502 $isDisplayLineItems = $this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
503
504 $this->assign('isDisplayLineItems', $isDisplayLineItems);
505
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.
97288cdc 509 $this->assign('is_quick_config', 1);
510 $this->_params['is_quick_config'] = 1;
511 }
512
24c1b3d8 513 if (!empty($params['selectProduct']) && $params['selectProduct'] !== 'no_thanks') {
9c1bc317 514 $option = $params['options_' . $params['selectProduct']] ?? NULL;
6a488035
TO
515 $productID = $params['selectProduct'];
516 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
517 $productID, $option
518 );
519 $this->set('productID', $productID);
520 $this->set('option', $option);
521 }
e46f73c7 522 if (CRM_Core_Component::isEnabled('CiviMember') && empty($this->_ccid)) {
6a488035 523 if (isset($params['selectMembership']) &&
24c1b3d8 524 $params['selectMembership'] !== 'no_thanks'
6a488035 525 ) {
42e3a033 526 $this->buildMembershipBlock(
5b757295 527 $this->_membershipContactID,
e622655c 528 $params['selectMembership']
6a488035 529 );
9cc96227 530 if (!empty($params['auto_renew'])) {
531 $this->assign('auto_renew', TRUE);
532 }
6a488035
TO
533 }
534 else {
535 $this->assign('membershipBlock', FALSE);
536 }
537 }
2f44fc96 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);
541 }
6a488035 542
a9653117 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'])
2f44fc96 547 ) && empty($this->_ccid)
a9653117 548 ) {
be2fb01f 549 $fieldTypes = ['Contact', 'Organization'];
6a488035 550 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
a13f3d8c 551 $fieldTypes = array_merge($fieldTypes, $contactSubType);
6a488035 552 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
be2fb01f 553 $fieldTypes = array_merge($fieldTypes, ['Membership']);
6a488035
TO
554 }
555 else {
be2fb01f 556 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
6a488035
TO
557 }
558
4779abb3 559 $this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
6a488035
TO
560 }
561
562 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
563 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
97288cdc 564
6a488035 565 $this->assign('priceSetID', $this->_priceSetId);
6a488035 566
229159bf
CW
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.
fb8d25da 570 if ($this->_contributeMode === 'notify' ||
a4859929 571 $this->_amount <= 0.0 || $this->_params['is_pay_later']
229159bf
CW
572 ) {
573 $contribButton = ts('Continue');
6a488035 574 }
fe552de9 575 elseif (!empty($this->_ccid)) {
576 $contribButton = ts('Make Payment');
fe552de9 577 }
6a488035 578 else {
229159bf 579 $contribButton = ts('Make Contribution');
6a488035 580 }
a4859929 581 $this->assign('button', $contribButton);
e364c762 582
583 $this->assign('continueText',
584 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
585 'is_payment_to_existing' => !empty($this->_ccid),
586 'amount' => $this->_amount,
1330f57a 587 ])
e364c762 588 );
589
be2fb01f 590 $this->addButtons([
1330f57a
SL
591 [
592 'type' => 'next',
593 'name' => $contribButton,
594 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
595 'isDefault' => TRUE,
1330f57a
SL
596 ],
597 [
598 'type' => 'back',
599 'name' => ts('Go Back'),
600 ],
601 ]);
6a488035 602
be2fb01f 603 $defaults = [];
9c80939e 604 $fields = array_fill_keys(array_keys($this->_fields), 1);
6a488035
TO
605 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
606
607 $contact = $this->_params;
608 foreach ($fields as $name => $dontCare) {
9c80939e 609 // Recursively set defaults for nested fields
fb8d25da 610 if (isset($contact[$name]) && is_array($contact[$name]) && ($name === 'onbehalf' || $name === 'honor')) {
9c80939e 611 foreach ($contact[$name] as $fieldName => $fieldValue) {
fb8d25da 612 if (is_array($fieldValue) && $this->_fields[$name][$fieldName]['html_type'] === 'CheckBox') {
38b95e0f 613 foreach ($fieldValue as $key => $value) {
614 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
615 }
616 }
617 else {
618 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
619 }
9c80939e
CW
620 }
621 }
622 elseif (isset($contact[$name])) {
6a488035 623 $defaults[$name] = $contact[$name];
fb8d25da 624 if (substr($name, 0, 7) === 'custom_') {
6a488035
TO
625 $timeField = "{$name}_time";
626 if (isset($contact[$timeField])) {
627 $defaults[$timeField] = $contact[$timeField];
628 }
629 if (isset($contact["{$name}_id"])) {
630 $defaults["{$name}_id"] = $contact["{$name}_id"];
631 }
632 }
be2fb01f 633 elseif (in_array($name, [
1330f57a
SL
634 'addressee',
635 'email_greeting',
636 'postal_greeting',
637 ]) && !empty($contact[$name . '_custom'])
a13f3d8c 638 ) {
6a488035
TO
639 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
640 }
641 }
642 }
643
644 $this->assign('useForMember', $this->get('useForMember'));
645
6a488035
TO
646 $this->setDefaults($defaults);
647
648 $this->freeze();
649 }
650
4b238552
MW
651 /**
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)
655 *
656 * @param int $cid
657 * Contact checked for having a current membership for a particular membership.
4b238552
MW
658 * @param int|array $selectedMembershipTypeID
659 * Selected membership id.
4b238552
MW
660 * @param null $isTest
661 *
662 * @return bool
663 * Is this a separate membership payment
664 *
665 * @throws \CiviCRM_API3_Exception
666 * @throws \CRM_Core_Exception
667 */
e622655c 668 private function buildMembershipBlock($cid, $selectedMembershipTypeID = NULL, $isTest = NULL) {
4b238552
MW
669 $separateMembershipPayment = FALSE;
670 if ($this->_membershipBlock) {
671 $this->_currentMemberships = [];
672
673 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
674 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember);
675
4b238552
MW
676 $autoRenewMembershipTypeOptions = [];
677
678 $separateMembershipPayment = $this->_membershipBlock['is_separate_payment'] ?? NULL;
679
680 if ($membershipPriceset) {
681 foreach ($this->_priceSet['fields'] as $pField) {
682 if (empty($pField['options'])) {
683 continue;
684 }
685 foreach ($pField['options'] as $opId => $opValues) {
686 if (empty($opValues['membership_type_id'])) {
687 continue;
688 }
689 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
690 }
691 }
692 }
693 elseif (!empty($this->_membershipBlock['membership_types'])) {
694 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
695 }
696
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',
701 $this->_mid,
702 'membership_type_id'
703 );
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');
706 }
707 }
708
709 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
710 $this->_membershipTypeValues = $membershipTypeValues;
711 $endDate = NULL;
712
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;
721 }
722 }
723 }
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']);
e622655c 730 if ($cid) {
4b238552
MW
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;
738 }
739 }
740 $membershipTypes[] = $memType;
741 }
742 }
743 elseif ($memType['is_active']) {
744
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;
750 }
751 else {
752 $javascriptMethod = NULL;
753 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
754 }
755
756 //add membership type.
757 $radio[$memType['id']] = NULL;
758 $radioOptAttrs[$memType['id']] = $javascriptMethod;
759 if ($cid) {
760 $membership = new CRM_Member_DAO_Membership();
761 $membership->contact_id = $cid;
762 $membership->membership_type_id = $memType['id'];
763
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');
767
768 if (!is_null($isTest)) {
769 $membership->is_test = $isTest;
770 }
771
772 //CRM-4297
773 $membership->orderBy('end_date DESC');
774
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);
780 continue;
781 }
782 $this->assign('renewal_mode', TRUE);
783 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
784 $memType['current_membership'] = $membership->end_date;
785 if (!$endDate) {
786 $endDate = $memType['current_membership'];
787 $this->_defaultMemTypeId = $memType['id'];
788 }
789 if ($memType['current_membership'] < $endDate) {
790 $endDate = $memType['current_membership'];
791 $this->_defaultMemTypeId = $memType['id'];
792 }
793 }
794 }
795 $membershipTypes[] = $memType;
796 }
797 }
798 }
799
800 $this->assign('membershipBlock', $this->_membershipBlock);
e622655c 801 $this->assign('showRadio', FALSE);
4b238552 802 $this->assign('membershipTypes', $membershipTypes);
4b238552
MW
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);
807
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']);
814 }
815 else {
816 $this->assign('autoRenewOption', $autoRenewOption);
817 }
4b238552
MW
818 }
819
820 return $separateMembershipPayment;
821 }
822
6a488035 823 /**
ab8fe4ef 824 * Overwrite action.
825 *
826 * Since we are only showing elements in frozen mode no help display needed.
6a488035
TO
827 *
828 * @return int
6a488035 829 */
00be9182 830 public function getAction() {
6a488035
TO
831 if ($this->_action & CRM_Core_Action::PREVIEW) {
832 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
833 }
834 else {
835 return CRM_Core_Action::VIEW;
836 }
837 }
838
839 /**
5e4f7f74 840 * Set default values for the form.
6a488035 841 *
5e4f7f74
EM
842 * Note that in edit/view mode
843 * the default values are retrieved from the database
6a488035 844 */
a13f3d8c
TO
845 public function setDefaultValues() {
846 }
6a488035
TO
847
848 /**
fe482240 849 * Process the form.
6a488035
TO
850 */
851 public function postProcess() {
da8d9879 852 $contactID = $this->getContactID();
77beddbe 853 try {
854 $result = $this->processFormSubmission($contactID);
855 }
856 catch (CRM_Core_Exception $e) {
857 $this->bounceOnError($e->getMessage());
858 }
859
75637f22 860 if (is_array($result) && !empty($result['is_payment_failure'])) {
77beddbe 861 $this->bounceOnError($result['error']->getMessage());
cc789d46 862 }
5fb28746
EM
863 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
864 $this->set('params', $this->_params);
75637f22 865 }
6a488035 866
75637f22
EM
867 /**
868 * Wrangle financial type ID.
869 *
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.
872 *
873 * Comments from previous refactor indicate doubt as to what was going on.
874 *
d1aed9dc 875 * @param int $financialTypeID
75637f22
EM
876 *
877 * @return null|string
878 */
d1aed9dc
MW
879 public function wrangleFinancialTypeID($financialTypeID) {
880 if (empty($financialTypeID) && !empty($this->_values['pledge_id'])) {
881 $financialTypeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
75637f22
EM
882 $this->_values['pledge_id'],
883 'financial_type_id'
884 );
6a488035 885 }
d1aed9dc 886 return $financialTypeID;
75637f22 887 }
6a488035 888
75637f22
EM
889 /**
890 * Process the form.
891 *
892 * @param array $premiumParams
893 * @param CRM_Contribute_BAO_Contribution $contribution
894 */
5fb28746 895 protected function postProcessPremium($premiumParams, $contribution) {
75637f22
EM
896 $hour = $minute = $second = 0;
897 // assigning Premium information to receipt tpl
9c1bc317 898 $selectProduct = $premiumParams['selectProduct'] ?? NULL;
75637f22
EM
899 if ($selectProduct &&
900 $selectProduct != 'no_thanks'
901 ) {
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);
cbbbf0ef 910 $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']] ?? NULL);
6a488035 911
75637f22 912 $periodType = $productDAO->period_type;
6a488035 913
75637f22
EM
914 if ($periodType) {
915 $fixed_period_start_day = $productDAO->fixed_period_start_day;
916 $duration_unit = $productDAO->duration_unit;
917 $duration_interval = $productDAO->duration_interval;
fb8d25da 918 if ($periodType === 'rolling') {
75637f22
EM
919 $startDate = date('Y-m-d');
920 }
fb8d25da 921 elseif ($periodType === 'fixed') {
75637f22
EM
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/>";
926 $year = $date[0];
927 $startDate = $year . '-' . $month . '-' . $day;
928 }
929 else {
930 $startDate = date('Y-m-d');
931 }
6a488035 932 }
6a488035 933
75637f22
EM
934 $date = explode('-', $startDate);
935 $year = $date[0];
936 $month = $date[1];
937 $day = $date[2];
6a488035 938
75637f22
EM
939 switch ($duration_unit) {
940 case 'year':
fb8d25da 941 $year += $duration_interval;
75637f22 942 break;
6a488035 943
75637f22 944 case 'month':
fb8d25da 945 $month += $duration_interval;
75637f22 946 break;
6a488035 947
75637f22 948 case 'day':
fb8d25da 949 $day += $duration_interval;
75637f22 950 break;
6a488035 951
75637f22 952 case 'week':
fb8d25da 953 $day += ($duration_interval * 7);
6a488035 954 }
75637f22
EM
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);
6a488035
TO
958 }
959
75637f22
EM
960 $dao = new CRM_Contribute_DAO_Premium();
961 $dao->entity_table = 'civicrm_contribution_page';
962 $dao->entity_id = $this->_id;
963 $dao->find(TRUE);
964 $this->assign('contact_phone', $dao->premiums_contact_phone);
965 $this->assign('contact_email', $dao->premiums_contact_email);
966
967 //create Premium record
be2fb01f 968 $params = [
75637f22
EM
969 'product_id' => $premiumParams['selectProduct'],
970 'contribution_id' => $contribution->id,
6b409353 971 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ?? NULL,
75637f22
EM
972 'quantity' => 1,
973 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
974 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
be2fb01f 975 ];
75637f22
EM
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;
6a488035 982 }
75637f22
EM
983 //Fixed For CRM-3901
984 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
985 $daoContrProd->contribution_id = $contribution->id;
986 if ($daoContrProd->find(TRUE)) {
987 $params['id'] = $daoContrProd->id;
6a488035 988 }
6a488035 989
75637f22
EM
990 CRM_Contribute_BAO_Contribution::addPremium($params);
991 if ($productDAO->cost && !empty($params['financial_type_id'])) {
be2fb01f 992 $trxnParams = [
75637f22
EM
993 'cost' => $productDAO->cost,
994 'currency' => $productDAO->currency,
995 'financial_type_id' => $params['financial_type_id'],
996 'contributionId' => $contribution->id,
be2fb01f 997 ];
75637f22 998 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
6a488035
TO
999 }
1000 }
fb8d25da 1001 elseif ($selectProduct === 'no_thanks') {
75637f22
EM
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();
6a488035
TO
1007 }
1008 }
75637f22 1009 }
6a488035 1010
75637f22
EM
1011 /**
1012 * Process the contribution.
1013 *
75637f22
EM
1014 * @param array $params
1015 * @param array $result
f6261e9d 1016 * @param array $contributionParams
1017 * Parameters to be passed to contribution create action.
3febe800 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.
1020 * - contact_id
1021 * - line_item
1022 * - is_test
1023 * - campaign_id
1024 * - contribution_page_id
1025 * - source
1026 * - payment_type_id
1027 * - thankyou_date (not all forms will set this)
1028 *
75637f22 1029 * @param CRM_Financial_DAO_FinancialType $financialType
75637f22
EM
1030 * @param int $billingLocationID
1031 * ID of billing location type.
10490499 1032 * @param bool $isRecur
1033 * Is this recurring?
75637f22
EM
1034 *
1035 * @return \CRM_Contribute_DAO_Contribution
12fde6ae 1036 *
1037 * @throws \CRM_Core_Exception
1038 * @throws \CiviCRM_API3_Exception
a281a8ea
EM
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.
1041 *
75637f22 1042 */
a281a8ea 1043 protected function processFormContribution(
75637f22
EM
1044 $params,
1045 $result,
f6261e9d 1046 $contributionParams,
75637f22 1047 $financialType,
449f4c90 1048 $billingLocationID,
1049 $isRecur
75637f22 1050 ) {
a281a8ea 1051 $form = $this;
75637f22 1052 $transaction = new CRM_Core_Transaction();
f6261e9d 1053 $contactID = $contributionParams['contact_id'];
1054
75637f22 1055 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
91768280 1056 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
cbbbf0ef 1057 $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : $form->_values['pledge_id'] ?? NULL;
75637f22 1058 if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
09108d7d 1059 (!empty($params['is_pledge']) || $pledgeID)) {
75637f22 1060 $isPledge = TRUE;
6a488035
TO
1061 }
1062 else {
75637f22 1063 $isPledge = FALSE;
6a488035
TO
1064 }
1065
75637f22
EM
1066 // add these values for the recurringContrib function ,CRM-10188
1067 $params['financial_type_id'] = $financialType->id;
6a488035 1068
3febe800 1069 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
6a488035 1070
75637f22
EM
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;
51e89def 1079 }
449f4c90 1080 $params['is_recur'] = $isRecur;
9c1bc317 1081 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ?? NULL;
449f4c90 1082 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
51e89def 1083
75637f22 1084 $now = date('YmdHis');
9c1bc317 1085 $receiptDate = $params['receipt_date'] ?? NULL;
75637f22
EM
1086 if ($isEmailReceipt) {
1087 $receiptDate = $now;
6a488035
TO
1088 }
1089
75637f22 1090 if (isset($params['amount'])) {
f6261e9d 1091 $contributionParams = array_merge(self::getContributionParams(
0ede7391 1092 $params, $financialType->id,
f6261e9d 1093 $result, $receiptDate,
1094 $recurringContributionID), $contributionParams
75637f22 1095 );
a281a8ea 1096 $contributionParams['non_deductible_amount'] = self::getNonDeductibleAmount($params, $financialType, TRUE, $form);
83644f47 1097 $contributionParams['skipCleanMoney'] = TRUE;
1098 // @todo this is the wrong place for this - it should be done as close to form submission
1099 // as possible
1100 $contributionParams['total_amount'] = $params['amount'];
77beddbe 1101
f6261e9d 1102 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
6a488035 1103
fe4d1285 1104 if (Civi::settings()->get('invoicing')) {
be2fb01f 1105 $dataArray = [];
f6261e9d 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.
75637f22
EM
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']])) {
2cfe2cf4 1112 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + $value['tax_amount'];
75637f22
EM
1113 }
1114 else {
2cfe2cf4 1115 $dataArray[$value['tax_rate']] = $value['tax_amount'];
75637f22
EM
1116 }
1117 }
6a488035
TO
1118 }
1119 }
75637f22
EM
1120 $smarty = CRM_Core_Smarty::singleton();
1121 $smarty->assign('dataArray', $dataArray);
75637f22 1122 }
6a488035 1123
75637f22
EM
1124 // lets store it in the form variable so postProcess hook can get to this and use it
1125 $form->_contributionID = $contribution->id;
1126 }
9af49867 1127 $form->assign('totalTaxAmount', $params['tax_amount'] ?? NULL);
6a488035 1128
7a13735b 1129 // process soft credit / pcp params first
1130 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
75637f22 1131
7a13735b 1132 //CRM-13981, processing honor contact into soft-credit contribution
1133 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
75637f22 1134
75637f22 1135 if ($isPledge) {
356bfcaf 1136 $form = self::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
6a488035 1137 }
6a488035 1138
a281a8ea 1139 if ($contribution) {
09108d7d 1140 CRM_Core_BAO_CustomValueTable::postProcess($params,
75637f22
EM
1141 'civicrm_contribution',
1142 $contribution->id,
1143 'Contribution'
1144 );
1145 }
75637f22
EM
1146 // Save note
1147 if ($contribution && !empty($params['contribution_note'])) {
be2fb01f 1148 $noteParams = [
75637f22
EM
1149 'entity_table' => 'civicrm_contribution',
1150 'note' => $params['contribution_note'],
1151 'entity_id' => $contribution->id,
1152 'contact_id' => $contribution->contact_id,
be2fb01f 1153 ];
75637f22 1154
be2fb01f 1155 CRM_Core_BAO_Note::add($noteParams, []);
cc789d46 1156 }
cc789d46 1157
75637f22
EM
1158 //create contribution activity w/ individual and target
1159 //activity w/ organisation contact id when onbelf, CRM-4027
d33f8fc4 1160 $actParams = [];
75637f22 1161 $targetContactID = NULL;
d33f8fc4
JP
1162 if (!empty($params['onbehalf_contact_id'])) {
1163 $actParams = [
1164 'source_contact_id' => $params['onbehalf_contact_id'],
1165 'on_behalf' => TRUE,
1166 ];
75637f22 1167 $targetContactID = $contribution->contact_id;
75637f22
EM
1168 }
1169
1170 // create an activity record
1171 if ($contribution) {
bf302610 1172 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
75637f22
EM
1173 }
1174
1175 $transaction->commit();
75637f22 1176 return $contribution;
6a488035
TO
1177 }
1178
1179 /**
75637f22 1180 * Create the recurring contribution record.
6a488035 1181 *
75637f22
EM
1182 * @param CRM_Core_Form $form
1183 * @param array $params
1184 * @param int $contactID
1185 * @param string $contributionType
75637f22 1186 *
449f4c90 1187 * @return int|null
6a488035 1188 */
9b1f9df3 1189 public static function processRecurringContribution($form, $params, $contactID, $contributionType) {
cde484fd 1190
449f4c90 1191 if (empty($params['is_recur'])) {
75637f22
EM
1192 return NULL;
1193 }
6a488035 1194
be2fb01f 1195 $recurParams = ['contact_id' => $contactID];
9c1bc317
CW
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;
f69a9ac3 1203 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
6a488035 1204
75637f22
EM
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'
1211 // CRM-16331
1212 && !empty($form->_membershipTypeValues)
1213 && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])
1214 ) {
1215 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1216 }
6a488035 1217
75637f22
EM
1218 $recurParams['is_test'] = 0;
1219 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1220 (isset($form->_mode) && ($form->_mode == 'test'))
1221 ) {
1222 $recurParams['is_test'] = 1;
1223 }
6a488035 1224
75637f22
EM
1225 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1226 if (!empty($params['receive_date'])) {
12e53254 1227 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
75637f22 1228 }
9c1bc317 1229 $recurParams['invoice_id'] = $params['invoiceID'] ?? NULL;
75637f22 1230 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
9c1bc317 1231 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ?? NULL;
eba1a1d7 1232 $recurParams['is_email_receipt'] = (bool) ($params['is_email_receipt'] ?? FALSE);
af1bffc2
MW
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']);
75637f22 1235 $recurParams['financial_type_id'] = $contributionType->id;
6a488035 1236
cbbbf0ef 1237 $campaignId = $params['campaign_id'] ?? $form->_values['campaign_id'] ?? NULL;
75637f22 1238 $recurParams['campaign_id'] = $campaignId;
75637f22
EM
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}";
1247 if ($form->_mode) {
1248 $urlParams .= "&mode={$form->_mode}";
1249 }
6a488035 1250 }
75637f22 1251 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
6a488035 1252 }
66c8ea62 1253 $form->_params['contributionRecurID'] = $recurring->id;
75637f22
EM
1254
1255 return $recurring->id;
6a488035
TO
1256 }
1257
1258 /**
75637f22 1259 * Add on behalf of organization and it's location.
cd6994fc 1260 *
75637f22
EM
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.
a1a94e61 1263 *
75637f22
EM
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.
9fc4e1d9 1269 *
75637f22
EM
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.
6a488035 1275 */
75637f22 1276 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
33260076 1277 $isNotCurrentEmployer = FALSE;
be2fb01f 1278 $dupeIDs = [];
75637f22 1279 $orgID = NULL;
6cc679d2 1280 if (!empty($behalfOrganization['organization_id'])) {
75637f22
EM
1281 $orgID = $behalfOrganization['organization_id'];
1282 unset($behalfOrganization['organization_id']);
33260076 1283 }
1284 // create employer relationship with $contactID only when new organization is there
1285 // else retain the existing relationship
1286 else {
33260076 1287 $isNotCurrentEmployer = TRUE;
bb06e9ed 1288 }
6a488035 1289
75637f22
EM
1290 if (!$orgID) {
1291 // check if matching organization contact exists
be2fb01f 1292 $dupeIDs = CRM_Contact_BAO_Contact::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
6a488035 1293
75637f22
EM
1294 // CRM-6243 says to pick the first org even if more than one match
1295 if (count($dupeIDs) >= 1) {
75c07fde 1296 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
75637f22
EM
1297 // don't allow name edit
1298 unset($behalfOrganization['organization_name']);
6a488035
TO
1299 }
1300 }
1301 else {
75637f22
EM
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']);
6a488035
TO
1306 }
1307
75637f22
EM
1308 // handling for image url
1309 if (!empty($behalfOrganization['image_URL'])) {
1310 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
6a488035
TO
1311 }
1312
75637f22 1313 // create organization, add location
e4addeb2 1314 $behalfOrganization['contact_type'] = 'Organization';
75637f22
EM
1315 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1316 NULL, NULL, 'Organization'
1317 );
1318 // create relationship
33260076 1319 if ($isNotCurrentEmployer) {
e4addeb2
JG
1320 try {
1321 \Civi\Api4\Relationship::create(FALSE)
1322 ->addValue('contact_id_a', $contactID)
1323 ->addValue('contact_id_b', $orgID)
dead2d66 1324 ->addValue('relationship_type_id', $relTypeId = CRM_Contact_BAO_RelationshipType::getEmployeeRelationshipTypeID())
e4addeb2
JG
1325 ->addValue('is_permission_a_b:name', 'View and update')
1326 ->execute();
1327 }
1328 catch (CRM_Core_Exception $e) {
1329 // Ignore if duplicate relationship.
1330 if ($e->getMessage() !== 'Duplicate Relationship') {
1331 throw $e;
1332 }
1333 }
33260076 1334 }
1f1740fe 1335
75637f22
EM
1336 // if multiple match - send a duplicate alert
1337 if ($dupeIDs && (count($dupeIDs) > 1)) {
1338 $values['onbehalf_dupe_alert'] = 1;
1339 // required for IPN
1340 $params['onbehalf_dupe_alert'] = 1;
6a488035 1341 }
cde484fd 1342
75637f22
EM
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.
6a488035 1348
75637f22
EM
1349 // required for mailing/template display ..etc
1350 $values['related_contact'] = $contactID;
6a488035 1351
0462a5b2 1352 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1353 $params['onbehalf_contact_id'] = $contactID;
1354
75637f22
EM
1355 //make this employee of relationship as current
1356 //employer / employee relationship, CRM-3532
33260076 1357 if ($isNotCurrentEmployer &&
75637f22
EM
1358 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1359 ) {
33260076 1360 $isNotCurrentEmployer = FALSE;
6a488035 1361 }
6a488035 1362
33260076 1363 if (!$isNotCurrentEmployer && $orgID) {
75637f22
EM
1364 //build current employer params
1365 $currentEmpParams[$contactID] = $orgID;
1366 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
6a488035 1367 }
6a488035 1368
75637f22
EM
1369 // contribution / signup will be done using this
1370 // organization id.
1371 $contactID = $orgID;
6a488035 1372 }
75637f22
EM
1373 }
1374
6a488035 1375 /**
5e4f7f74
EM
1376 * Function used to se pcp related defaults / params.
1377 *
1378 * This is used by contribution and also event PCPs
6a488035 1379 *
014c4014
TO
1380 * @param CRM_Core_Form $page
1381 * Form object.
1382 * @param array $params
6a488035 1383 *
cd6994fc 1384 * @return array
6a488035 1385 */
26f76772 1386 public static function processPcp(&$page, $params): array {
547206bc 1387 $params['pcp_made_through_id'] = $page->_pcpId;
6a488035 1388 $page->assign('pcpBlock', TRUE);
8cc574cf 1389 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
6a488035
TO
1390 $params['pcp_roll_nickname'] = ts('Anonymous');
1391 $params['pcp_is_anonymous'] = 1;
1392 }
1393 else {
1394 $params['pcp_is_anonymous'] = 0;
1395 }
be2fb01f 1396 foreach ([
1330f57a
SL
1397 'pcp_display_in_roll',
1398 'pcp_is_anonymous',
1399 'pcp_roll_nickname',
1400 'pcp_personal_note',
1401 ] as $val) {
a7488080 1402 if (!empty($params[$val])) {
6a488035
TO
1403 $page->assign($val, $params[$val]);
1404 }
1405 }
1406
1407 return $params;
1408 }
705b4205
EM
1409
1410 /**
5e4f7f74
EM
1411 * Process membership.
1412 *
5624f515 1413 * @param array $membershipParams
014c4014 1414 * @param int $contactID
5624f515
EM
1415 * @param array $customFieldsFormatted
1416 * @param array $fieldTypes
1417 * @param array $premiumParams
014c4014
TO
1418 * @param array $membershipLineItems
1419 * Line items specifically relating to memberships.
705b4205 1420 */
4b6c8c1e 1421 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
26f76772 1422 $membershipLineItems): void {
8bc79dfc 1423
4b6c8c1e 1424 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1425 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
be2fb01f 1426 $membershipType = empty($membershipTypes) ? [] : reset($membershipTypes);
5624f515 1427
cbbbf0ef 1428 $this->assign('membership_name', $membershipType['name']);
9c1bc317 1429 $this->_values['membership_name'] = $membershipType['name'] ?? NULL;
7c113627 1430
4b6c8c1e 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;
1438 }
1bec3b51 1439 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id);
7c113627 1440
1bec3b51 1441 if ($this->isFormSupportsNonMembershipContributions()) {
4b6c8c1e 1442 $financialTypeID = $this->_values['financial_type_id'];
705b4205 1443 }
4b6c8c1e 1444 else {
cbbbf0ef 1445 $financialTypeID = $membershipType['financial_type_id'] ?? $membershipParams['financial_type_id'] ?? NULL;
705b4205 1446 }
4b6c8c1e 1447
f3acfdd9 1448 if (!empty($this->_params['membership_source'])) {
4b6c8c1e 1449 $membershipParams['contribution_source'] = $this->_params['membership_source'];
1450 }
1451
1775d73b 1452 $this->postProcessMembership($membershipParams, $contactID, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $financialTypeID,
5b9d3ce8 1453 $membershipLineItems);
4b6c8c1e 1454
1455 $this->assign('membership_assign', TRUE);
1456 $this->set('membershipTypeID', $membershipParams['selectMembership']);
705b4205 1457 }
fb49fa48 1458
8bc79dfc 1459 /**
668ddfc2
EM
1460 * Process the Memberships.
1461 *
1462 * @param array $membershipParams
1463 * Array of membership fields.
1464 * @param int $contactID
1465 * Contact id.
668ddfc2
EM
1466 *
1467 * @param array $premiumParams
1468 * @param null $customFieldsFormatted
1469 * @param null $includeFieldTypes
1470 *
1471 * @param array $membershipDetails
1472 *
1473 * @param array $membershipTypeIDs
1474 *
1475 * @param bool $isPaidMembership
1476 * @param array $membershipID
1477 *
1478 * @param bool $isProcessSeparateMembershipTransaction
1479 *
1480 * @param int $financialTypeID
f2bca231 1481 * @param array $unprocessedLineItems
1482 * Line items for payment options chosen on the form.
668ddfc2
EM
1483 *
1484 * @throws \CRM_Core_Exception
5b9d3ce8
MWMC
1485 * @throws \CiviCRM_API3_Exception
1486 * @throws \Civi\Payment\Exception\PaymentProcessorException
668ddfc2
EM
1487 */
1488 protected function postProcessMembership(
1775d73b 1489 $membershipParams, $contactID, $premiumParams,
ff708ff0 1490 $customFieldsFormatted, $includeFieldTypes, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
5b9d3ce8 1491 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
1775d73b
EM
1492 // Assign $this to $form while we eliminate it.
1493 $form = $this;
82583880 1494 $membershipContribution = NULL;
cbbbf0ef 1495 $isTest = $membershipParams['is_test'] ?? FALSE;
be2fb01f 1496 $errors = $paymentResults = [];
858f7096 1497 $form->_values['isMembership'] = TRUE;
cbbbf0ef 1498 $isRecurForFirstTransaction = $form->_params['is_recur'] ?? $membershipParams['is_recur'] ?? NULL;
f2bca231 1499
858f7096 1500 $totalAmount = $membershipParams['amount'];
449f4c90 1501
668ddfc2
EM
1502 if ($isPaidMembership) {
1503 if ($isProcessSeparateMembershipTransaction) {
1504 // If we have 2 transactions only one can use the invoice id.
1505 $membershipParams['invoiceID'] .= '-2';
449f4c90 1506 if (!empty($membershipParams['auto_renew'])) {
1507 $isRecurForFirstTransaction = FALSE;
1508 }
668ddfc2
EM
1509 }
1510
417c6834 1511 if (!$isProcessSeparateMembershipTransaction) {
f2bca231 1512 // Skip line items in the contribution processing transaction.
1513 // We will create them with the membership for proper linking.
417c6834 1514 $membershipParams['skipLineItem'] = 1;
1515 }
8e8d287f 1516 else {
1517 $membershipParams['total_amount'] = $totalAmount;
f2bca231 1518 $membershipParams['skipLineItem'] = 0;
8e8d287f 1519 CRM_Price_BAO_LineItem::getLineItemArray($membershipParams);
1520
1521 }
1775d73b 1522 $paymentResult = $this->processConfirm(
f2bca231 1523 $membershipParams,
5fb28746 1524 $contactID,
668ddfc2 1525 $financialTypeID,
449f4c90 1526 $isTest,
1527 $isRecurForFirstTransaction
668ddfc2 1528 );
82583880 1529 if (!empty($paymentResult['contribution'])) {
be2fb01f 1530 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentResult];
5fb28746 1531 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
668ddfc2
EM
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;
1537 }
1538 }
1539
1540 if ($isProcessSeparateMembershipTransaction) {
1541 try {
f2bca231 1542 $form->_lineItem = $unprocessedLineItems;
668ddfc2
EM
1543 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1544 unset($membershipParams['is_recur']);
1545 }
4596b5c5 1546 [$membershipContribution, $secondPaymentResult] = $this->processSecondaryFinancialTransaction($contactID, array_merge($membershipParams, ['skipLineItem' => 1]),
cbbbf0ef 1547 $isTest, $unprocessedLineItems, $membershipDetails['minimum_fee'] ?? 0, $membershipDetails['financial_type_id'] ?? NULL);
be2fb01f 1548 $paymentResults[] = ['contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult];
d275cdb2 1549 $totalAmount = $membershipContribution->total_amount;
668ddfc2
EM
1550 }
1551 catch (CRM_Core_Exception $e) {
1552 $errors[2] = $e->getMessage();
1553 $membershipContribution = NULL;
1554 }
1555 }
1556
1557 $membership = NULL;
1558 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1559 $membershipContributionID = $membershipContribution->id;
1560 }
1561
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'];
1565 }
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)) {
cbbbf0ef 1568 $typesTerms = $membershipParams['types_terms'] ?? [];
65e172a3 1569
be2fb01f 1570 $membershipLines = $nonMembershipLines = [];
65e172a3 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'];
1575 }
1576 }
1577 }
1578
1579 $i = 1;
be2fb01f 1580 $form->_params['createdMembershipIDs'] = [];
668ddfc2 1581 foreach ($membershipTypeIDs as $memType) {
be2fb01f 1582 $membershipLineItems = [];
65e172a3 1583 if ($i < count($membershipTypeIDs)) {
1584 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1585 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1586 }
1587 else {
1588 $membershipLineItems = $unprocessedLineItems;
1589 }
1590 $i++;
cbbbf0ef 1591 $numTerms = $typesTerms[$memType] ?? 1;
77c21b32 1592 $contributionRecurID = $form->_params['contributionRecurID'] ?? NULL;
668ddfc2
EM
1593
1594 $membershipSource = NULL;
1595 if (!empty($form->_params['membership_source'])) {
1596 $membershipSource = $form->_params['membership_source'];
1597 }
6489e3de
SL
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;
668ddfc2
EM
1601 }
1602 $isPayLater = NULL;
1603 if (isset($form->_params)) {
9c1bc317 1604 $isPayLater = $form->_params['is_pay_later'] ?? NULL;
668ddfc2 1605 }
5fbbde1f 1606 $memParams = [
1607 'campaign_id' => $form->_params['campaign_id'] ?? ($form->_values['campaign_id'] ?? NULL),
1608 ];
668ddfc2 1609
5b9d3ce8
MWMC
1610 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1611 if (!empty($membershipContribution)) {
3ec3dcbe 1612 $pending = $membershipContribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
5b9d3ce8
MWMC
1613 }
1614 else {
cbbbf0ef
MW
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'])
1619 ) &&
1620 (($this->_values['is_monetary'] && $this->_amount > 0.0))
1621 ) {
1622 $pending = TRUE;
1623 }
1624 $pending = FALSE;
5b9d3ce8 1625 }
cbbbf0ef 1626
ddb56033 1627 [$membership, $renewalMode, $dates] = self::legacyProcessMembership(
668ddfc2 1628 $contactID, $memType, $isTest,
cbbbf0ef 1629 date('YmdHis'), $membershipParams['cms_contactID'] ?? NULL,
668ddfc2
EM
1630 $customFieldsFormatted,
1631 $numTerms, $membershipID, $pending,
05f80619 1632 $contributionRecurID, $membershipSource, $isPayLater, $memParams, $membershipContribution,
65e172a3 1633 $membershipLineItems
668ddfc2 1634 );
bd53b1b9 1635
668ddfc2
EM
1636 $form->set('renewal_mode', $renewalMode);
1637 if (!empty($dates)) {
1fc22ffa 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'));
668ddfc2
EM
1640 }
1641
1642 if (!empty($membershipContribution)) {
c9cc6e3a
MWMC
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,
1648 ];
1649 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
668ddfc2 1650 }
040728f5
AF
1651 if ($membership) {
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;
1655
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;
1659 }
668ddfc2
EM
1660 }
1661 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1662 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
e894942a
WA
1663 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id == $priceFieldOp['membership_type_id']) {
1664 $membershipOb = $membership;
56f54f02 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) : '-';
668ddfc2
EM
1667 }
1668 else {
1669 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1670 }
1671 }
1672 $form->_values['lineItem'] = $form->_lineItem;
1673 $form->assign('lineItem', $form->_lineItem);
1674 }
1675 }
1676
1677 if (!empty($errors)) {
1678 $message = $this->compileErrorMessage($errors);
1679 throw new CRM_Core_Exception($message);
1680 }
28da8ecd 1681
82583880
EM
1682 if (isset($membershipContributionID)) {
1683 $form->_values['contribution_id'] = $membershipContributionID;
1684 }
a506739a 1685
1fc22ffa 1686 if (empty($form->_params['is_pay_later']) && $form->_paymentProcessor) {
a506739a 1687 // the is_monetary concept probably should be deprecated as it can be calculated from
1688 // the existence of 'amount' & seems fragile.
668ddfc2
EM
1689 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1690 // call postProcess hook before leaving
1691 $form->postProcessHook();
668ddfc2 1692 }
a506739a 1693
82583880 1694 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
fe3dbce1 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!
be2fb01f 1698 $paymentParams = array_merge($form->_params, ['contributionID' => $form->_values['contribution_other_id']]);
b43ed44b
PN
1699
1700 // CRM-19792 : set necessary fields for payment processor
1701 CRM_Core_Payment_Form::mapParams($form->_bltID, $paymentParams, $paymentParams, TRUE);
1702
15816cb4
AS
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');
be2fb01f 1707 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult];
15816cb4 1708 }
668ddfc2
EM
1709 // Do not send an email if Recurring transaction is done via Direct Mode
1710 // Email will we sent when the IPN is received.
63137f3a 1711 foreach ($paymentResults as $result) {
7c864699
TL
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']);
1715 }
63137f3a 1716 }
668ddfc2
EM
1717 return;
1718 }
1719
1fc22ffa 1720 $emailValues = array_merge($membershipParams, $form->_values);
1721 $emailValues['membership_assign'] = 1;
05d09dc4
JP
1722 $emailValues['useForMember'] = !empty($form->_useForMember);
1723
858f7096 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;
858f7096 1728 $emailValues['amount'] = 0;
036c6315 1729
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
bd53b1b9 1733 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
18135422 1734 if (empty($form->_paymentProcessor)) {
1735 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
cbbbf0ef 1736 $paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_values['payment_processor'] ?? NULL);
036c6315 1737 $this->_paymentProcessor['id'] = $paymentProcessorIDs[0];
1738 }
be2fb01f 1739 $result = ['payment_status_id' => 1, 'contribution' => $membershipContribution];
036c6315 1740 $this->completeTransaction($result, $result['contribution']->id);
1741 }
1e584dec
JP
1742 // return as completeTransaction() already sends the receipt mail.
1743 return;
858f7096 1744 }
1fc22ffa 1745
668ddfc2 1746 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
858f7096 1747 $emailValues,
668ddfc2
EM
1748 $isTest, FALSE,
1749 $includeFieldTypes
1750 );
1751 }
1752
1753 /**
1754 * Turn array of errors into message string.
1755 *
1756 * @param array $errors
1757 *
1758 * @return string
1759 */
1760 protected function compileErrorMessage($errors) {
1761 foreach ($errors as $error) {
1762 if (is_string($error)) {
1763 $message[] = $error;
1764 }
1765 }
1766 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1767 }
1768
1769 /**
1770 * Where a second separate financial transaction is supported we will process it here.
1771 *
1772 * @param int $contactID
668ddfc2
EM
1773 * @param array $tempParams
1774 * @param bool $isTest
1775 * @param array $lineItems
1776 * @param $minimumFee
1777 * @param int $financialTypeID
1778 *
4596b5c5
EM
1779 * @return array []
1780 *
1781 * @throws \CRM_Core_Exception
1782 * @throws \CiviCRM_API3_Exception
1783 * @throws \Civi\Payment\Exception\PaymentProcessorException
668ddfc2 1784 */
4596b5c5
EM
1785 private function processSecondaryFinancialTransaction($contactID, $tempParams, $isTest, $lineItems, $minimumFee,
1786 $financialTypeID): array {
668ddfc2
EM
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));
9c1bc317 1792 $isRecur = $tempParams['is_recur'] ?? NULL;
668ddfc2 1793
668ddfc2
EM
1794 //assign receive date when separate membership payment
1795 //and contribution amount not selected.
4596b5c5 1796 if ($this->_amount == 0) {
668ddfc2 1797 $now = date('YmdHis');
4596b5c5 1798 $this->_params['receive_date'] = $now;
668ddfc2 1799 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
4596b5c5
EM
1800 $this->set('params', $this->_params);
1801 $this->assign('receive_date', $receiveDate);
668ddfc2
EM
1802 }
1803
4596b5c5
EM
1804 $this->set('membership_amount', $minimumFee);
1805 $this->assign('membership_amount', $minimumFee);
668ddfc2 1806
668ddfc2
EM
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.
4596b5c5 1811 $this->_params['separate_membership_payment'] = 1;
be2fb01f 1812 $contributionParams = [
3febe800 1813 'contact_id' => $contactID,
1814 'line_item' => $lineItems,
1815 'is_test' => $isTest,
4596b5c5
EM
1816 'campaign_id' => $tempParams['campaign_id'] ?? $this->_values['campaign_id'] ?? NULL,
1817 'contribution_page_id' => $this->_id,
cbbbf0ef 1818 'source' => $tempParams['source'] ?? $tempParams['description'] ?? NULL,
be2fb01f 1819 ];
4596b5c5 1820 $isMonetary = !empty($this->_values['is_monetary']);
3febe800 1821 if ($isMonetary) {
1822 if (empty($paymentParams['is_pay_later'])) {
4596b5c5 1823 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
3febe800 1824 }
1825 }
b43ed44b
PN
1826
1827 // CRM-19792 : set necessary fields for payment processor
4596b5c5 1828 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $tempParams, TRUE);
b43ed44b 1829
a281a8ea 1830 $membershipContribution = $this->processFormContribution(
668ddfc2 1831 $tempParams,
0193ebdb 1832 $tempParams,
3febe800 1833 $contributionParams,
668ddfc2 1834 $financialType,
4596b5c5 1835 $this->_bltID,
449f4c90 1836 $isRecur
668ddfc2 1837 );
0193ebdb 1838
be2fb01f 1839 $result = [];
15816cb4 1840
7f5ae3a0
AS
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;
15816cb4 1852
4596b5c5 1853 if ($this->_values['is_monetary'] && !$this->_params['is_pay_later'] && $minimumFee > 0.0) {
0193ebdb 1854 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1855 // now we compensate here.
4596b5c5 1856 if (empty($this->_paymentProcessor['object'])) {
0193ebdb 1857 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1858 }
1859 else {
4596b5c5 1860 $payment = $this->_paymentProcessor['object'];
0193ebdb 1861 }
1862 $result = $payment->doPayment($tempParams, 'contribute');
4596b5c5
EM
1863 $this->set('membership_trx_id', $result['trxn_id']);
1864 $this->assign('membership_trx_id', $result['trxn_id']);
0193ebdb 1865 }
1866
be2fb01f 1867 return [$membershipContribution, $result];
668ddfc2
EM
1868 }
1869
fb49fa48 1870 /**
5e4f7f74 1871 * Are we going to do 2 financial transactions.
fb49fa48 1872 *
5e4f7f74
EM
1873 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1874 * contribution
81355da3 1875 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
fb49fa48 1876 *
014c4014 1877 * @param int $formID
fb49fa48
EM
1878 *
1879 * @return bool
1880 */
1bec3b51 1881 protected function isSeparateMembershipTransaction($formID): bool {
fb49fa48 1882 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1bec3b51 1883 if (!empty($memBlockDetails['is_separate_payment']) && $this->isFormSupportsNonMembershipContributions()) {
fb49fa48
EM
1884 return TRUE;
1885 }
1886 return FALSE;
1887 }
df6c4f28
EM
1888
1889 /**
5e4f7f74
EM
1890 * This function sets the fields.
1891 *
df6c4f28
EM
1892 * - $this->_params['amount_level']
1893 * - $this->_params['selectMembership']
1894 * And under certain circumstances sets
1895 * $this->_params['amount'] = null;
1896 *
100fef9d 1897 * @param int $priceSetID
df6c4f28
EM
1898 */
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();
06b4ee3e 1905 $paramWeDoNotUnderstand = NULL;
df6c4f28
EM
1906
1907 while ($priceField->fetch()) {
df6c4f28
EM
1908 if ($priceField->name == "contribution_amount") {
1909 $paramWeDoNotUnderstand = $priceField->id;
1910 }
1911 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1912 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
c039f658 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.
df6c4f28
EM
1917 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1918 $this->_params["price_{$priceField->id}"], 'label');
1919 }
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');
1923 }
5e4f7f74
EM
1924 }
1925 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1926 // as membership amount.
df6c4f28
EM
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
f64a217a 1931 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
df6c4f28 1932 elseif (
b99f3e96 1933 !empty($this->_membershipBlock['is_separate_payment'])
df6c4f28
EM
1934 && !empty($this->_values['fee'][$priceField->id])
1935 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
cbbbf0ef 1936 && ($this->_params["price_{$paramWeDoNotUnderstand}"] ?? NULL) < 1
df6c4f28
EM
1937 && empty($this->_params["price_{$priceField->id}"])
1938 ) {
a13f3d8c 1939 $this->_params['amount'] = NULL;
df6c4f28
EM
1940 }
1941
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
32c3b33f 1947 if (!empty($this->_membershipBlock['is_separate_payment'])
3c0201c9 1948 && !empty($this->_values['fee'][$priceField->id])
cbbbf0ef
MW
1949 && ($this->_values['fee'][$priceField->id]['name'] ?? NULL) == 'contribution_amount'
1950 && ($this->_params["price_{$priceField->id}"] ?? NULL) == '-1'
df6c4f28 1951 ) {
a13f3d8c 1952 $this->_params['amount'] = NULL;
df6c4f28
EM
1953 }
1954 }
1955 }
be26f3e0 1956
03110609 1957 /**
5e4f7f74
EM
1958 * Submit function.
1959 *
03110609
EM
1960 * @param array $params
1961 *
d6c86ce5
EM
1962 * @throws \CRM_Core_Exception
1963 * @throws \CiviCRM_API3_Exception
1964 * @throws \Civi\API\Exception\UnauthorizedException
03110609 1965 */
00be9182 1966 public static function submit($params) {
be26f3e0
EM
1967 $form = new CRM_Contribute_Form_Contribution_Confirm();
1968 $form->_id = $params['id'];
75637f22 1969
f64a217a
EM
1970 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1971 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
be26f3e0
EM
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));
ec57bf87 1976
be26f3e0 1977 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
58315149 1978
1979 $order = new CRM_Financial_BAO_Order();
d6c86ce5 1980 $order->setPriceSetIDByContributionPageID($params['id']);
58315149 1981 $order->setPriceSelectionFromUnfilteredInput($params);
d6c86ce5 1982 if (isset($params['amount']) && !CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id)) {
58315149 1983 // @todo deprecate receiving amount, calculate on the form.
2df49c85 1984 $order->setOverrideTotalAmount((float) $params['amount']);
58315149 1985 }
1986 $amount = $order->getTotalAmount();
765d02a3
EM
1987 if ($form->_separateMembershipPayment) {
1988 $amount -= $order->getMembershipTotalAmount();
1989 }
1990 $form->_amount = $params['amount'] = $form->_params['amount'] = $amount;
870156d6 1991 // hack these in for test support.
1992 $form->_fields['billing_first_name'] = 1;
1993 $form->_fields['billing_last_name'] = 1;
dccd9f4f 1994 // CRM-18854 - Set form values to allow pledge to be created for api test.
de6c59ca 1995 if (!empty($params['pledge_block_id'])) {
9c1bc317 1996 $form->_values['pledge_id'] = $params['pledge_id'] ?? NULL;
dccd9f4f
ERL
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;
2003 }
be26f3e0
EM
2004 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
2005 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
f64a217a
EM
2006 $priceSetFields = reset($priceFields);
2007 $form->_values['fee'] = $priceSetFields['fields'];
5624f515 2008 $form->_priceSetId = $priceSetID;
be26f3e0 2009 $form->setFormAmountFields($priceSetID);
be2fb01f 2010 $capabilities = [];
18135422 2011 if ($form->_mode) {
2012 $capabilities[] = (ucfirst($form->_mode) . 'Mode');
2013 }
2014 $form->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
77c21b32 2015 $form->_params['payment_processor_id'] = $params['payment_processor_id'] ?? 0;
04b24bb5 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']];
2019 }
e02d7e96 2020 if (!empty($params['payment_processor_id'])) {
0f2b049e 2021 // The concept of contributeMode is deprecated as is the billing_mode concept.
a13f3d8c 2022 if ($form->_paymentProcessor['billing_mode'] == 1) {
e6fa4056
EM
2023 $form->_contributeMode = 'direct';
2024 }
2025 else {
2026 $form->_contributeMode = 'notify';
2027 }
d25e4224 2028 }
65e172a3 2029
ed781038
JP
2030 if (!empty($params['useForMember'])) {
2031 $form->set('useForMember', 1);
2032 $form->_useForMember = 1;
2033 }
be26f3e0 2034 $priceFields = $priceFields[$priceSetID]['fields'];
d6c86ce5
EM
2035
2036 $form->_lineItem = [$priceSetID => $order->getLineItems()];
be2fb01f 2037 $membershipPriceFieldIDs = [];
d6c86ce5 2038 foreach ($order->getLineItems() as $lineItem) {
65e172a3 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'];
2044 }
2045 }
2046 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
35bdddf0 2047 $form->setRecurringMembershipParams();
cbbbf0ef 2048 $form->processFormSubmission($params['contact_id'] ?? NULL);
be26f3e0
EM
2049 }
2050
2051 /**
ceb9fecb
EM
2052 * Helper function for static submit function.
2053 *
2054 * Set relevant params - help us to build up an array that we can pass in.
5e4f7f74 2055 *
100fef9d 2056 * @param int $id
be26f3e0
EM
2057 * @param array $params
2058 *
2059 * @return array
2060 * @throws CiviCRM_API3_Exception
2061 */
00be9182 2062 public static function getFormParams($id, array $params) {
a13f3d8c 2063 if (!isset($params['is_pay_later'])) {
e02d7e96 2064 if (!empty($params['payment_processor_id'])) {
d25e4224
DG
2065 $params['is_pay_later'] = 0;
2066 }
62e432ac 2067 elseif (($params['amount'] ?? 0) !== 0) {
be2fb01f 2068 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
a13f3d8c 2069 'id' => $id,
21dfd5f5 2070 'return' => 'is_pay_later',
be2fb01f 2071 ]);
d25e4224 2072 }
be26f3e0 2073 }
a13f3d8c 2074 if (empty($params['price_set_id'])) {
be26f3e0
EM
2075 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
2076 }
2077 return $params;
2078 }
96025800 2079
75637f22
EM
2080 /**
2081 * Post form submission handling.
2082 *
2083 * This is also called from the test suite.
2084 *
2085 * @param int $contactID
2086 *
2087 * @return array
fb8d25da 2088 *
62c41ada 2089 * @throws \CRM_Core_Exception
fb8d25da 2090 * @throws \CiviCRM_API3_Exception
2091 * @throws \Civi\API\Exception\UnauthorizedException
75637f22
EM
2092 */
2093 protected function processFormSubmission($contactID) {
858f7096 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;
2098 }
036c6315 2099 if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] === 0) {
75637f22
EM
2100 $this->_params['is_pay_later'] = $isPayLater = TRUE;
2101 }
58466af1 2102
2103 if (!empty($this->_ccid)) {
2104 $this->_params['contribution_id'] = $this->_ccid;
2105 }
67c998f4
JP
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];
2111 }
2112 }
2113 }
75637f22 2114 // add a description field at the very beginning
6489e3de
SL
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);
75637f22 2117
9c1bc317 2118 $this->_params['accountingCode'] = $this->_values['accountingCode'] ?? NULL;
75637f22
EM
2119
2120 // fix currency ID
2121 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
2122
a55e39e9 2123 CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($this->_params);
2124
dccd9f4f 2125 // CRM-18854
f3acfdd9 2126 if (!empty($this->_params['is_pledge']) && empty($this->_values['pledge_id']) && !empty($this->_values['adjust_recur_start_date'])) {
dccd9f4f 2127 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
b99f3e96
CW
2128 if (!empty($this->_params['start_date']) || empty($pledgeBlock['is_pledge_start_date_visible'])
2129 || empty($pledgeBlock['is_pledge_start_date_editable'])) {
9c1bc317 2130 $pledgeStartDate = $this->_params['start_date'] ?? NULL;
dccd9f4f
ERL
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);
2134 }
2135 }
2136
75637f22 2137 //carry payment processor id.
f3acfdd9 2138 if (!empty($this->_paymentProcessor['id'])) {
75637f22
EM
2139 $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
2140 }
f85b8063
KJ
2141
2142 $premiumParams = $membershipParams = $params = $this->_params;
75637f22
EM
2143 if (!empty($params['image_URL'])) {
2144 CRM_Contact_BAO_Contact::processImageParams($params);
2145 }
f85b8063 2146
be2fb01f 2147 $fields = ['email-Primary' => 1];
75637f22
EM
2148
2149 // get the add to groups
be2fb01f 2150 $addToGroups = [];
75637f22
EM
2151
2152 // now set the values for the billing location.
2153 foreach ($this->_fields as $name => $value) {
2154 $fields[$name] = 1;
2155
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'];
2159 }
2160 }
2161
bddc8a28 2162 $fields = $this->formatParamsForPaymentProcessor($fields);
75637f22
EM
2163
2164 // billing email address
2165 $fields["email-{$this->_bltID}"] = 1;
2166
75637f22
EM
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.
2f44fc96 2171 if (!empty($this->_values['onbehalf_profile_id']) && empty($this->_ccid)) {
be2fb01f
CW
2172 $behalfOrganization = [];
2173 $orgFields = ['organization_name', 'organization_id', 'org_option'];
75637f22
EM
2174 foreach ($orgFields as $fld) {
2175 if (array_key_exists($fld, $params)) {
2176 $behalfOrganization[$fld] = $params[$fld];
2177 unset($params[$fld]);
2178 }
2179 }
2180
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;
2185 }
2186 elseif (!(strstr($fld, '-'))) {
be2fb01f 2187 if (in_array($fld, [
75637f22
EM
2188 'contribution_campaign_id',
2189 'member_campaign_id',
be2fb01f 2190 ])) {
75637f22
EM
2191 $fld = 'campaign_id';
2192 }
2193 else {
2194 $behalfOrganization[$fld] = $values;
2195 }
2196 $this->_params[$fld] = $values;
2197 }
2198 }
2199 }
2200
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_') {
2205 continue;
2206 }
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;
2214 }
2215 }
2216 }
2217 unset($params['onbehalf_location']);
2218 }
2219 if (!empty($params['onbehalf[image_URL]'])) {
2220 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2221 }
2222 }
2223
2224 // check for profile double opt-in and get groups to be subscribed
2225 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
2226
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]);
2232 }
2233 }
2234 }
2235
2236 foreach ($addToGroups as $k) {
2237 if (array_key_exists($k, $subscribeGroupIds)) {
2238 unset($addToGroups[$k]);
2239 }
2240 }
2241
2242 if (empty($contactID)) {
2243 $dupeParams = $params;
2244 if (!empty($dupeParams['onbehalf'])) {
2245 unset($dupeParams['onbehalf']);
2246 }
2247 if (!empty($dupeParams['honor'])) {
2248 unset($dupeParams['honor']);
2249 }
2250
be2fb01f 2251 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
75637f22
EM
2252
2253 // Fetch default greeting id's if creating a contact
2254 if (!$contactID) {
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);
2258 }
2259 }
2260 }
2261 $contactType = NULL;
2262 }
2263 else {
2264 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2265 }
2266 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
2267 $params,
2268 $fields,
2269 $contactID,
2270 $addToGroups,
2271 NULL,
2272 $contactType,
2273 TRUE
2274 );
2275
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;
2281
2282 //get email primary first if exist
cbbbf0ef 2283 $subscriptionEmail = ['email' => $params['email-Primary'] ?? NULL];
75637f22 2284 if (!$subscriptionEmail['email']) {
9c1bc317 2285 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ?? NULL;
75637f22
EM
2286 }
2287 // subscribing contact to groups
2288 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2289 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2290 }
2291
2292 // If onbehalf-of-organization contribution / signup, add organization
2293 // and it's location.
a9653117 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'])
2298 )
2299 ) {
be2fb01f 2300 $ufFields = [];
75637f22
EM
2301 foreach ($this->_fields['onbehalf'] as $name => $value) {
2302 $ufFields[$name] = 1;
2303 }
2304 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
2305 $this->_params, $ufFields
2306 );
2307 }
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;
2315 }
2316
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);
2322 }
2323 else {
2324 $session->set('transaction.userID', NULL);
2325 }
2326
2327 $this->_useForMember = $this->get('useForMember');
2328
2329 // store the fact that this is a membership and membership type is selected
c6f840fa 2330 if ($this->isMembershipSelected($membershipParams)) {
f2bca231 2331 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem);
75637f22
EM
2332 }
2333 else {
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;
f2bca231 2338 // Make it explict that we are letting the processConfirm function figure out the line items.
2339 $paymentParams['skipLineItem'] = 0;
75637f22 2340
1659de20
PN
2341 if (!isset($paymentParams['line_item'])) {
2342 $paymentParams['line_item'] = $this->_lineItem;
2343 }
2344
75637f22
EM
2345 if (!empty($paymentParams['onbehalf']) &&
2346 is_array($paymentParams['onbehalf'])
2347 ) {
2348 foreach ($paymentParams['onbehalf'] as $key => $value) {
2349 if (strstr($key, 'custom_')) {
2350 $this->_params[$key] = $value;
2351 }
2352 }
75637f22 2353 }
10490499 2354
1a3545fa 2355 $result = $this->processConfirm($paymentParams,
5fb28746 2356 $contactID,
46763692 2357 $this->wrangleFinancialTypeID($this->_values['financial_type_id']),
449f4c90 2358 ($this->_mode == 'test') ? 1 : 0,
cbbbf0ef 2359 $paymentParams['is_recur'] ?? NULL
75637f22 2360 );
82583880 2361
0193ebdb 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']);
2365 }
2366 if (!empty($result['contribution'])) {
04b24bb5 2367 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
0193ebdb 2368 $this->completeTransaction($result, $result['contribution']->id);
a8a4259e
EM
2369 }
2370 return $result;
75637f22
EM
2371 }
2372 }
2373
c6f840fa
MWMC
2374 /**
2375 * Return True/False if we have a membership selected on the contribution page
2376 * @param array $membershipParams
2377 *
2378 * @return bool
2379 */
2380 private function isMembershipSelected($membershipParams) {
2381 $priceFieldIds = $this->get('memberPriceFieldIDS');
2382 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2383 && empty($priceFieldIds)) {
2384 return TRUE;
2385 }
2386 else {
2387 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2388 }
2389 return !empty($membershipParams['selectMembership']);
2390 }
2391
2392 /**
2393 * Extract the selected memberships from a priceSet
2394 *
2395 * @param array $membershipParams
2396 *
2397 * @return array
2398 */
2399 private function getMembershipParamsFromPriceSet($membershipParams) {
2400 $priceFieldIds = $this->get('memberPriceFieldIDS');
2401 if (empty($priceFieldIds)) {
2402 return $membershipParams;
2403 }
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;
2414 }
2415 }
2416 $membershipParams['selectMembership'] = $membershipTypeIds;
2417 $membershipParams['types_terms'] = $membershipTypeTerms;
2418 return $membershipParams;
2419 }
2420
7dd9ca37
EM
2421 /**
2422 * Membership processing section.
2423 *
2424 * This is in a separate function as part of a move towards refactoring.
2425 *
2426 * @param int $contactID
2427 * @param array $membershipParams
2428 * @param array $premiumParams
f2bca231 2429 * @param array $formLineItems
7dd9ca37 2430 */
f2bca231 2431 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
c8ce9261
EM
2432 if (!$this->_useForMember) {
2433 $this->assign('membership_assign', TRUE);
2434 $this->set('membershipTypeID', $this->_params['selectMembership']);
2435 }
2436
2437 if ($this->_action & CRM_Core_Action::PREVIEW) {
2438 $membershipParams['is_test'] = 1;
2439 }
2440 if ($this->_params['is_pay_later']) {
2441 $membershipParams['is_pay_later'] = 1;
2442 }
2443
2444 if (isset($this->_params['onbehalf_contact_id'])) {
2445 $membershipParams['onbehalf_contact_id'] = $this->_params['onbehalf_contact_id'];
2446 }
2447 //inherit campaign from contribution page.
2448 if (!array_key_exists('campaign_id', $membershipParams)) {
2449 $membershipParams['campaign_id'] = $this->_values['campaign_id'] ?? NULL;
2450 }
2451
2452 $this->_params = CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
2453
0d9ff2d4 2454 // This could be set by a hook.
2455 if (!empty($this->_params['installments'])) {
2456 $membershipParams['installments'] = $this->_params['installments'];
2457 }
7dd9ca37
EM
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'];
2461 }
2462 else {
2463 $membershipParams['cms_contactID'] = $contactID;
2464 }
2465
2466 if (!empty($membershipParams['onbehalf']) &&
2467 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2468 ) {
2469 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2470 }
2471
be2fb01f 2472 $customFieldsFormatted = $fieldTypes = [];
7dd9ca37
EM
2473 if (!empty($membershipParams['onbehalf']) &&
2474 is_array($membershipParams['onbehalf'])
2475 ) {
2476 foreach ($membershipParams['onbehalf'] as $key => $value) {
2477 if (strstr($key, 'custom_')) {
2478 $customFieldId = explode('_', $key);
2479 CRM_Core_BAO_CustomField::formatCustomField(
2480 $customFieldId[1],
2481 $customFieldsFormatted,
2482 $value,
2483 'Membership',
2484 NULL,
2485 $contactID
2486 );
2487 }
2488 }
be2fb01f 2489 $fieldTypes = ['Contact', 'Organization', 'Membership'];
7dd9ca37
EM
2490 }
2491
c6f840fa 2492 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
7dd9ca37
EM
2493 if (!empty($membershipParams['selectMembership'])) {
2494 // CRM-12233
f2bca231 2495 $membershipLineItems = $formLineItems;
1bec3b51 2496 if ($this->_separateMembershipPayment && $this->isFormSupportsNonMembershipContributions()) {
be2fb01f 2497 $membershipLineItems = [];
7dd9ca37
EM
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]);
2503 break;
2504 }
2505 }
2506 }
4b6c8c1e 2507 try {
f2bca231 2508 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
4b6c8c1e 2509 }
d23860d8
SP
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());
2515 }
2516 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2517 }
4b6c8c1e 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']}"));
2521 }
7dd9ca37
EM
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
2528 );
2529 }
2530 }
2531 }
2532
0193ebdb 2533 /**
2534 * Complete transaction if payment has been processed.
2535 *
2536 * Check the result for a success outcome & if paid then complete the transaction.
2537 *
2538 * Completing will trigger update of related entities and emails.
2539 *
2540 * @param array $result
2541 * @param int $contributionID
2542 *
ec7e3954
E
2543 * @throws \CiviCRM_API3_Exception
2544 * @throws \Exception
0193ebdb 2545 */
2546 protected function completeTransaction($result, $contributionID) {
cbbbf0ef 2547 if (($result['payment_status_id'] ?? NULL) == 1) {
0193ebdb 2548 try {
be2fb01f 2549 civicrm_api3('contribution', 'completetransaction', [
a55e39e9 2550 'id' => $contributionID,
6b409353 2551 'trxn_id' => $result['trxn_id'] ?? NULL,
cbbbf0ef 2552 'payment_processor_id' => $result['payment_processor_id'] ?? $this->_paymentProcessor['id'],
a55e39e9 2553 'is_transactional' => FALSE,
6b409353
CW
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,
be2fb01f 2558 ]);
0193ebdb 2559 }
2560 catch (CiviCRM_API3_Exception $e) {
2561 if ($e->getErrorCode() != 'contribution_completed') {
f30b037a 2562 \Civi::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
0193ebdb 2563 throw new CRM_Core_Exception('Failed to update contribution in database');
2564 }
2565 }
2566 }
2567 }
2568
77beddbe 2569 /**
2570 * Bounce the user back to retry when an error occurs.
2571 *
2572 * @param string $message
2573 */
2574 protected function bounceOnError($message) {
2575 CRM_Core_Session::singleton()
2576 ->setStatus(ts("Payment Processor Error message :") .
2577 $message);
2578 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
2579 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
2580 ));
2581 }
2582
74c1b622 2583 /**
2584 * Is a payment being made.
2585 *
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
2589 *
2590 * @return bool
2591 */
2592 protected static function isPaymentTransaction($form) {
2593 return $form->_amount >= 0.0;
2594 }
2595
2596 /**
2597 * Process payment after confirmation.
2598 *
74c1b622 2599 * @param array $paymentParams
2600 * Array with payment related key.
2601 * value pairs
2602 * @param int $contactID
2603 * Contact id.
2604 * @param int $financialTypeID
2605 * Financial type id.
2606 * @param bool $isTest
2607 * @param bool $isRecur
2608 *
2609 * @throws CRM_Core_Exception
2610 * @throws Exception
2611 * @return array
2612 * associated array
74c1b622 2613 */
1a3545fa 2614 public function processConfirm(
74c1b622 2615 &$paymentParams,
2616 $contactID,
2617 $financialTypeID,
2618 $isTest,
2619 $isRecur
fb8d25da 2620 ): array {
1a3545fa 2621 $form = $this;
74c1b622 2622 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
2623 $isPaymentTransaction = self::isPaymentTransaction($form);
2624
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);
2631 }
2632
2633 // add some financial type details to the params list
2634 // if folks need to use it
c2978fe0 2635 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $financialType->id;
74c1b622 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;
2638 //CRM-11456
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;
2642
2643 //fix for CRM-16317
2644 if (empty($form->_params['receive_date'])) {
2645 $form->_params['receive_date'] = date('YmdHis');
2646 }
2647 if (!empty($form->_params['start_date'])) {
2648 $form->_params['start_date'] = date('YmdHis');
2649 }
2650 $form->assign('receive_date',
2651 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
2652 );
2653
2654 if (empty($form->_values['amount'])) {
2655 // If the amount is not in _values[], set it
2656 $form->_values['amount'] = $form->_params['amount'];
2657 }
2658
2659 if (isset($paymentParams['contribution_source'])) {
2660 $paymentParams['source'] = $paymentParams['contribution_source'];
2661 }
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)),
2668 ];
2669
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));
2674 }
2675 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
2676 else {
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', [
2680 1 => $form->_id,
2681 2 => $contributionParams['source'],
2682 ]),
2683 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
2684 220
2685 );
2686 }
2687
2688 if (isset($paymentParams['line_item'])) {
2689 // @todo make sure this is consisently set at this point.
2690 $contributionParams['line_item'] = $paymentParams['line_item'];
2691 }
2692 if (!empty($form->_paymentProcessor)) {
2693 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
2694 }
a281a8ea 2695 $contribution = $this->processFormContribution(
74c1b622 2696 $paymentParams,
2697 NULL,
2698 $contributionParams,
2699 $financialType,
74c1b622 2700 $form->_bltID,
2701 $isRecur
2702 );
2ebe2e8c 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
99ee765c 2705 if (isset($this->_params['related_contact'])) {
2706 $contactID = $this->_params['related_contact'];
2ebe2e8c 2707 }
99ee765c 2708 elseif (isset($this->_params['cms_contactID'])) {
2709 $contactID = $this->_params['cms_contactID'];
2ebe2e8c 2710 }
99ee765c 2711 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($this->_params,
2ebe2e8c 2712 $contactID,
2713 'email-' . $form->_bltID
2714 );
74c1b622 2715
2716 $paymentParams['item_name'] = $form->_params['description'];
2717
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];
2723 }
2724
2725 $paymentParams['contributionID'] = $contribution->id;
2726 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
2727
2728 if (!empty($form->_params['is_recur']) && $contribution->contribution_recur_id) {
2729 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
2730 }
2731 if (isset($paymentParams['contribution_source'])) {
2732 $form->_params['source'] = $paymentParams['contribution_source'];
2733 }
2734
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;
2739 }
2740
2741 $form->_values['contribution_id'] = $contribution->id;
2742 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
2743
2744 if (!empty($form->_paymentProcessor)) {
2745 try {
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();
2751 }
2752 $result = $payment->doPayment($paymentParams);
2753 $form->_params = array_merge($form->_params, $result);
816ce926
MW
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'];
74c1b622 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,
2761 $form->_values,
2762 $contribution->is_test
2763 );
2764 }
2765 return $result;
2766 }
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());
2772 }
2773 if (!empty($paymentParams['contributionRecurID'])) {
2774 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
2775 }
2776
2777 $result['is_payment_failure'] = TRUE;
2778 $result['error'] = $e;
2779 return $result;
2780 }
2781 }
2782 }
2783
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);
2787
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...).
2792 return [
2793 'payment_status_id' => 1,
2794 'contribution' => $contribution,
2795 'payment_processor_id' => 0,
2796 ];
2797 }
2798
2799 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
2800 $form->_values,
2801 $contribution->is_test
2802 );
2803 }
2804
ddb56033
EM
2805 /**
2806 * Temporary function to allow unit tests to access function being refactored away.
2807 *
2808 * @param int $contactID
2809 * @param int $membershipTypeID
2810 * @param int $membershipID
2811 *
2812 * @return array
2813 * @throws \CRM_Core_Exception
2814 * @throws \CiviCRM_API3_Exception
2815 */
2816 public static function unitTestAccessTolegacyProcessMembership($contactID, $membershipTypeID, $membershipID = NULL) {
2817 return self::legacyProcessMembership(
2818 $contactID,
2819 $membershipTypeID,
2820 0,
2821 NULL,
2822 NULL,
2823 NULL,
2824 1,
2825 $membershipID,
2826 NULL,
2827 NULL,
2828 FALSE,
2829 NULL
2830 );
2831 }
2832
5187a13c
EM
2833 /**
2834 * Interim function for processing memberships - this is being refactored out of existence.
2835 *
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
2844 * @param $pending
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
2851 *
2852 * @return array
2853 * @throws \CRM_Core_Exception
2854 * @throws \CiviCRM_API3_Exception
2855 */
ddb56033 2856 protected static function legacyProcessMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
5187a13c
EM
2857 $renewalMode = $updateStatusId = FALSE;
2858 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
2859 $format = '%Y%m%d';
2860 $statusFormat = '%Y-%m-%d';
2861 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
2862 $dates = [];
2863 $ids = [];
2864
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
2869 );
2870 if ($currentMembership) {
2871 $renewalMode = TRUE;
2872
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),
2878 // CRM-15475
2879 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2880 ])) {
2881
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',
2893 ], $memParams);
2894 if ($contributionRecurID) {
2895 $memParams['contribution_recur_id'] = $contributionRecurID;
2896 }
2897
2898 $membership = CRM_Member_BAO_Membership::create($memParams);
2899 return [$membership, $renewalMode, $dates];
2900 }
2901
2902 // Check and fix the membership if it is STALE
2903 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2904
2905 // Now Renew the membership
2906 if (!$currentMembership['is_current_member']) {
2907 // membership is not CURRENT
2908
2909 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2910 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
2911 $changeToday,
2912 $membershipTypeID,
2913 $numRenewTerms
2914 );
2915
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;
2919 }
2920 $currentMembership['is_test'] = $is_test;
2921
2922 if (!empty($membershipSource)) {
2923 $currentMembership['source'] = $membershipSource;
2924 }
2925
2926 if (!empty($currentMembership['id'])) {
2927 $ids['membership'] = $currentMembership['id'];
2928 }
2929 $memParams = array_merge($currentMembership, $memParams);
2930 $memParams['membership_type_id'] = $membershipTypeID;
2931
2932 //set the log start date.
2933 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2934 }
2935 else {
2936
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,
2943 $changeToday,
2944 $membershipTypeID,
2945 $numRenewTerms
2946 );
2947
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;
2953
2954 //set the log start date.
2955 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2956
2957 //CRM-18067
2958 if (!empty($membershipSource)) {
2959 $memParams['source'] = $membershipSource;
2960 }
2961 elseif (empty($membership->source)) {
2962 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
2963 $currentMembership['id'],
2964 'source'
2965 );
2966 }
2967
2968 if (!empty($currentMembership['id'])) {
2969 $ids['membership'] = $currentMembership['id'];
2970 }
2971 $memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed';
2972 }
2973 }
2974 else {
2975 // NEW Membership
2976 $memParams = array_merge([
2977 'contact_id' => $contactID,
2978 'membership_type_id' => $membershipTypeID,
2979 ], $memParams);
2980
2981 if (!$pending) {
2982 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2983
2984 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
2985 $memParams[$dateType] = $dates[$dateType] ?? NULL;
2986 }
2987
2988 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
2989 $statusFormat
2990 ),
2991 CRM_Utils_Date::customFormat($dates['end_date'],
2992 $statusFormat
2993 ),
2994 CRM_Utils_Date::customFormat($dates['join_date'],
2995 $statusFormat
2996 ),
2997 'now',
2998 TRUE,
2999 $membershipTypeID,
3000 $memParams
3001 );
3002 $updateStatusId = $status['id'] ?? NULL;
3003 }
3004 else {
3005 // if IPN/Pay-Later set status to: PENDING
3006 $updateStatusId = array_search('Pending', $allStatus);
3007 }
3008
3009 if (!empty($membershipSource)) {
3010 $memParams['source'] = $membershipSource;
3011 }
3012 $memParams['is_test'] = $is_test;
3013 $memParams['is_pay_later'] = $isPayLater;
3014 }
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;
3019 }
3020 //CRM-4555
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;
3026 }
3027
3028 //since we are renewing,
3029 //make status override false.
3030 $memParams['is_override'] = FALSE;
3031
3032 //CRM-4027, create log w/ individual contact.
3033 if ($modifiedID) {
3034 // @todo this param is likely unused now.
3035 $memParams['is_for_organization'] = TRUE;
3036 }
3037 $params['modified_id'] = $modifiedID ?? $contactID;
3038
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);
3046
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);
3050
3051 return [$membership, $renewalMode, $dates];
3052 }
3053
6a488035 3054}