Groups filter hack for smaller groups listings
[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);
6a488035
TO
490 $amount_block_is_active = $this->get('amount_block_is_active');
491 $this->assign('amount_block_is_active', $amount_block_is_active);
492
147b56dc
MW
493 // Make a copy of line items array to use for display only
494 $tplLineItems = $this->_lineItem;
97288cdc 495 if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
f1b56c48 496 // @todo $params seems like exactly the wrong place to get totalTaxAmount from
497 // this is a calculated variable so we it should be transparent how we
498 // calculated it rather than coming from 'params'
03b412ae
PB
499 $this->assign('totalTaxAmount', $params['tax_amount']);
500 }
f1b56c48 501 $this->assignLineItemsToTemplate($tplLineItems);
502
503 $isDisplayLineItems = $this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
504
505 $this->assign('isDisplayLineItems', $isDisplayLineItems);
506
507 if (!$isDisplayLineItems) {
508 // quickConfig is deprecated in favour of isDisplayLineItems. Lots of logic has been harnessed to quick config
509 // whereas isDisplayLineItems is specific & clear.
97288cdc 510 $this->assign('is_quick_config', 1);
511 $this->_params['is_quick_config'] = 1;
512 }
513
24c1b3d8 514 if (!empty($params['selectProduct']) && $params['selectProduct'] !== 'no_thanks') {
9c1bc317 515 $option = $params['options_' . $params['selectProduct']] ?? NULL;
6a488035
TO
516 $productID = $params['selectProduct'];
517 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
518 $productID, $option
519 );
520 $this->set('productID', $productID);
521 $this->set('option', $option);
522 }
523 $config = CRM_Core_Config::singleton();
2f44fc96 524 if (in_array('CiviMember', $config->enableComponents) && empty($this->_ccid)) {
6a488035 525 if (isset($params['selectMembership']) &&
24c1b3d8 526 $params['selectMembership'] !== 'no_thanks'
6a488035 527 ) {
42e3a033 528 $this->buildMembershipBlock(
5b757295 529 $this->_membershipContactID,
e622655c 530 $params['selectMembership']
6a488035 531 );
9cc96227 532 if (!empty($params['auto_renew'])) {
533 $this->assign('auto_renew', TRUE);
534 }
6a488035
TO
535 }
536 else {
537 $this->assign('membershipBlock', FALSE);
538 }
539 }
2f44fc96 540 if (empty($this->_ccid)) {
541 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
542 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
543 }
6a488035 544
a9653117 545 if (!empty($this->_values['onbehalf_profile_id']) &&
546 !empty($params['onbehalf']) &&
547 ($this->_values['is_for_organization'] == 2 ||
548 !empty($params['is_for_organization'])
2f44fc96 549 ) && empty($this->_ccid)
a9653117 550 ) {
be2fb01f 551 $fieldTypes = ['Contact', 'Organization'];
6a488035 552 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
a13f3d8c 553 $fieldTypes = array_merge($fieldTypes, $contactSubType);
6a488035 554 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
be2fb01f 555 $fieldTypes = array_merge($fieldTypes, ['Membership']);
6a488035
TO
556 }
557 else {
be2fb01f 558 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
6a488035
TO
559 }
560
4779abb3 561 $this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
6a488035
TO
562 }
563
564 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
565 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
97288cdc 566
6a488035 567 $this->assign('priceSetID', $this->_priceSetId);
6a488035 568
229159bf
CW
569 // The concept of contributeMode is deprecated.
570 // the is_monetary concept probably should be too as it can be calculated from
571 // the existence of 'amount' & seems fragile.
fb8d25da 572 if ($this->_contributeMode === 'notify' ||
a4859929 573 $this->_amount <= 0.0 || $this->_params['is_pay_later']
229159bf
CW
574 ) {
575 $contribButton = ts('Continue');
6a488035 576 }
fe552de9 577 elseif (!empty($this->_ccid)) {
578 $contribButton = ts('Make Payment');
fe552de9 579 }
6a488035 580 else {
229159bf 581 $contribButton = ts('Make Contribution');
6a488035 582 }
a4859929 583 $this->assign('button', $contribButton);
e364c762 584
585 $this->assign('continueText',
586 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
587 'is_payment_to_existing' => !empty($this->_ccid),
588 'amount' => $this->_amount,
1330f57a 589 ])
e364c762 590 );
591
be2fb01f 592 $this->addButtons([
1330f57a
SL
593 [
594 'type' => 'next',
595 'name' => $contribButton,
596 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
597 'isDefault' => TRUE,
1330f57a
SL
598 ],
599 [
600 'type' => 'back',
601 'name' => ts('Go Back'),
602 ],
603 ]);
6a488035 604
be2fb01f 605 $defaults = [];
9c80939e 606 $fields = array_fill_keys(array_keys($this->_fields), 1);
6a488035
TO
607 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
608
609 $contact = $this->_params;
610 foreach ($fields as $name => $dontCare) {
9c80939e 611 // Recursively set defaults for nested fields
fb8d25da 612 if (isset($contact[$name]) && is_array($contact[$name]) && ($name === 'onbehalf' || $name === 'honor')) {
9c80939e 613 foreach ($contact[$name] as $fieldName => $fieldValue) {
fb8d25da 614 if (is_array($fieldValue) && $this->_fields[$name][$fieldName]['html_type'] === 'CheckBox') {
38b95e0f 615 foreach ($fieldValue as $key => $value) {
616 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
617 }
618 }
619 else {
620 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
621 }
9c80939e
CW
622 }
623 }
624 elseif (isset($contact[$name])) {
6a488035 625 $defaults[$name] = $contact[$name];
fb8d25da 626 if (substr($name, 0, 7) === 'custom_') {
6a488035
TO
627 $timeField = "{$name}_time";
628 if (isset($contact[$timeField])) {
629 $defaults[$timeField] = $contact[$timeField];
630 }
631 if (isset($contact["{$name}_id"])) {
632 $defaults["{$name}_id"] = $contact["{$name}_id"];
633 }
634 }
be2fb01f 635 elseif (in_array($name, [
1330f57a
SL
636 'addressee',
637 'email_greeting',
638 'postal_greeting',
639 ]) && !empty($contact[$name . '_custom'])
a13f3d8c 640 ) {
6a488035
TO
641 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
642 }
643 }
644 }
645
646 $this->assign('useForMember', $this->get('useForMember'));
647
6a488035
TO
648 $this->setDefaults($defaults);
649
650 $this->freeze();
651 }
652
4b238552
MW
653 /**
654 * Build Membership Block in Contribution Pages.
655 * @todo this was shared on CRM_Contribute_Form_ContributionBase but we are refactoring and simplifying for each
656 * step (main/confirm/thankyou)
657 *
658 * @param int $cid
659 * Contact checked for having a current membership for a particular membership.
4b238552
MW
660 * @param int|array $selectedMembershipTypeID
661 * Selected membership id.
4b238552
MW
662 * @param null $isTest
663 *
664 * @return bool
665 * Is this a separate membership payment
666 *
667 * @throws \CiviCRM_API3_Exception
668 * @throws \CRM_Core_Exception
669 */
e622655c 670 private function buildMembershipBlock($cid, $selectedMembershipTypeID = NULL, $isTest = NULL) {
4b238552
MW
671 $separateMembershipPayment = FALSE;
672 if ($this->_membershipBlock) {
673 $this->_currentMemberships = [];
674
675 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
676 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember);
677
678 $allowAutoRenewMembership = $autoRenewOption = FALSE;
679 $autoRenewMembershipTypeOptions = [];
680
681 $separateMembershipPayment = $this->_membershipBlock['is_separate_payment'] ?? NULL;
682
683 if ($membershipPriceset) {
684 foreach ($this->_priceSet['fields'] as $pField) {
685 if (empty($pField['options'])) {
686 continue;
687 }
688 foreach ($pField['options'] as $opId => $opValues) {
689 if (empty($opValues['membership_type_id'])) {
690 continue;
691 }
692 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
693 }
694 }
695 }
696 elseif (!empty($this->_membershipBlock['membership_types'])) {
697 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
698 }
699
700 if (!empty($membershipTypeIds)) {
701 //set status message if wrong membershipType is included in membershipBlock
702 if (isset($this->_mid) && !$membershipPriceset) {
703 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
704 $this->_mid,
705 'membership_type_id'
706 );
707 if (!in_array($membershipTypeID, $membershipTypeIds)) {
708 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
709 }
710 }
711
712 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
713 $this->_membershipTypeValues = $membershipTypeValues;
714 $endDate = NULL;
715
716 // Check if we support auto-renew on this contribution page
717 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
718 // auto-renew payment even if that processor is not selected.
719 $allowAutoRenewOpt = TRUE;
720 if (is_array($this->_paymentProcessors)) {
721 foreach ($this->_paymentProcessors as $id => $val) {
722 if ($id && !$val['is_recur']) {
723 $allowAutoRenewOpt = FALSE;
724 }
725 }
726 }
727 foreach ($membershipTypeIds as $value) {
728 $memType = $membershipTypeValues[$value];
729 if ($selectedMembershipTypeID != NULL) {
730 if ($memType['id'] == $selectedMembershipTypeID) {
731 $this->assign('minimum_fee', $memType['minimum_fee'] ?? NULL);
732 $this->assign('membership_name', $memType['name']);
e622655c 733 if ($cid) {
4b238552
MW
734 $membership = new CRM_Member_DAO_Membership();
735 $membership->contact_id = $cid;
736 $membership->membership_type_id = $memType['id'];
737 if ($membership->find(TRUE)) {
738 $this->assign('renewal_mode', TRUE);
739 $memType['current_membership'] = $membership->end_date;
740 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
741 }
742 }
743 $membershipTypes[] = $memType;
744 }
745 }
746 elseif ($memType['is_active']) {
747
748 if ($allowAutoRenewOpt) {
749 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
750 $isAvailableAutoRenew = $this->_membershipBlock['auto_renew'][$value] ?? 1;
751 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
752 $allowAutoRenewMembership = TRUE;
753 }
754 else {
755 $javascriptMethod = NULL;
756 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
757 }
758
759 //add membership type.
760 $radio[$memType['id']] = NULL;
761 $radioOptAttrs[$memType['id']] = $javascriptMethod;
762 if ($cid) {
763 $membership = new CRM_Member_DAO_Membership();
764 $membership->contact_id = $cid;
765 $membership->membership_type_id = $memType['id'];
766
767 //show current membership, skip pending and cancelled membership records,
768 //because we take first membership record id for renewal
769 $membership->whereAdd('status_id != 5 AND status_id !=6');
770
771 if (!is_null($isTest)) {
772 $membership->is_test = $isTest;
773 }
774
775 //CRM-4297
776 $membership->orderBy('end_date DESC');
777
778 if ($membership->find(TRUE)) {
779 if (!$membership->end_date) {
780 unset($radio[$memType['id']]);
781 unset($radioOptAttrs[$memType['id']]);
782 $this->assign('islifetime', TRUE);
783 continue;
784 }
785 $this->assign('renewal_mode', TRUE);
786 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
787 $memType['current_membership'] = $membership->end_date;
788 if (!$endDate) {
789 $endDate = $memType['current_membership'];
790 $this->_defaultMemTypeId = $memType['id'];
791 }
792 if ($memType['current_membership'] < $endDate) {
793 $endDate = $memType['current_membership'];
794 $this->_defaultMemTypeId = $memType['id'];
795 }
796 }
797 }
798 $membershipTypes[] = $memType;
799 }
800 }
801 }
802
803 $this->assign('membershipBlock', $this->_membershipBlock);
e622655c 804 $this->assign('showRadio', FALSE);
4b238552
MW
805 $this->assign('membershipTypes', $membershipTypes);
806 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
807 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
808 //give preference to user submitted auto_renew value.
809 $takeUserSubmittedAutoRenew = (!empty($_POST) || $this->isSubmitted());
810 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
811
812 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
813 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
814 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
815 //options for different organisation is selected on the contribution page.
816 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
817 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
818 }
819 else {
820 $this->assign('autoRenewOption', $autoRenewOption);
821 }
4b238552
MW
822 }
823
824 return $separateMembershipPayment;
825 }
826
6a488035 827 /**
ab8fe4ef 828 * Overwrite action.
829 *
830 * Since we are only showing elements in frozen mode no help display needed.
6a488035
TO
831 *
832 * @return int
6a488035 833 */
00be9182 834 public function getAction() {
6a488035
TO
835 if ($this->_action & CRM_Core_Action::PREVIEW) {
836 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
837 }
838 else {
839 return CRM_Core_Action::VIEW;
840 }
841 }
842
843 /**
5e4f7f74 844 * Set default values for the form.
6a488035 845 *
5e4f7f74
EM
846 * Note that in edit/view mode
847 * the default values are retrieved from the database
6a488035 848 */
a13f3d8c
TO
849 public function setDefaultValues() {
850 }
6a488035
TO
851
852 /**
fe482240 853 * Process the form.
6a488035
TO
854 */
855 public function postProcess() {
da8d9879 856 $contactID = $this->getContactID();
77beddbe 857 try {
858 $result = $this->processFormSubmission($contactID);
859 }
860 catch (CRM_Core_Exception $e) {
861 $this->bounceOnError($e->getMessage());
862 }
863
75637f22 864 if (is_array($result) && !empty($result['is_payment_failure'])) {
77beddbe 865 $this->bounceOnError($result['error']->getMessage());
cc789d46 866 }
5fb28746
EM
867 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
868 $this->set('params', $this->_params);
75637f22 869 }
6a488035 870
75637f22
EM
871 /**
872 * Wrangle financial type ID.
873 *
874 * 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
875 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
876 *
877 * Comments from previous refactor indicate doubt as to what was going on.
878 *
d1aed9dc 879 * @param int $financialTypeID
75637f22
EM
880 *
881 * @return null|string
882 */
d1aed9dc
MW
883 public function wrangleFinancialTypeID($financialTypeID) {
884 if (empty($financialTypeID) && !empty($this->_values['pledge_id'])) {
885 $financialTypeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
75637f22
EM
886 $this->_values['pledge_id'],
887 'financial_type_id'
888 );
6a488035 889 }
d1aed9dc 890 return $financialTypeID;
75637f22 891 }
6a488035 892
75637f22
EM
893 /**
894 * Process the form.
895 *
896 * @param array $premiumParams
897 * @param CRM_Contribute_BAO_Contribution $contribution
898 */
5fb28746 899 protected function postProcessPremium($premiumParams, $contribution) {
75637f22
EM
900 $hour = $minute = $second = 0;
901 // assigning Premium information to receipt tpl
9c1bc317 902 $selectProduct = $premiumParams['selectProduct'] ?? NULL;
75637f22
EM
903 if ($selectProduct &&
904 $selectProduct != 'no_thanks'
905 ) {
906 $startDate = $endDate = "";
907 $this->assign('selectPremium', TRUE);
908 $productDAO = new CRM_Contribute_DAO_Product();
909 $productDAO->id = $selectProduct;
910 $productDAO->find(TRUE);
911 $this->assign('product_name', $productDAO->name);
912 $this->assign('price', $productDAO->price);
913 $this->assign('sku', $productDAO->sku);
cbbbf0ef 914 $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']] ?? NULL);
6a488035 915
75637f22 916 $periodType = $productDAO->period_type;
6a488035 917
75637f22
EM
918 if ($periodType) {
919 $fixed_period_start_day = $productDAO->fixed_period_start_day;
920 $duration_unit = $productDAO->duration_unit;
921 $duration_interval = $productDAO->duration_interval;
fb8d25da 922 if ($periodType === 'rolling') {
75637f22
EM
923 $startDate = date('Y-m-d');
924 }
fb8d25da 925 elseif ($periodType === 'fixed') {
75637f22
EM
926 if ($fixed_period_start_day) {
927 $date = explode('-', date('Y-m-d'));
928 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
929 $day = substr($fixed_period_start_day, -2) . "<br/>";
930 $year = $date[0];
931 $startDate = $year . '-' . $month . '-' . $day;
932 }
933 else {
934 $startDate = date('Y-m-d');
935 }
6a488035 936 }
6a488035 937
75637f22
EM
938 $date = explode('-', $startDate);
939 $year = $date[0];
940 $month = $date[1];
941 $day = $date[2];
6a488035 942
75637f22
EM
943 switch ($duration_unit) {
944 case 'year':
fb8d25da 945 $year += $duration_interval;
75637f22 946 break;
6a488035 947
75637f22 948 case 'month':
fb8d25da 949 $month += $duration_interval;
75637f22 950 break;
6a488035 951
75637f22 952 case 'day':
fb8d25da 953 $day += $duration_interval;
75637f22 954 break;
6a488035 955
75637f22 956 case 'week':
fb8d25da 957 $day += ($duration_interval * 7);
6a488035 958 }
75637f22
EM
959 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
960 $this->assign('start_date', $startDate);
961 $this->assign('end_date', $endDate);
6a488035
TO
962 }
963
75637f22
EM
964 $dao = new CRM_Contribute_DAO_Premium();
965 $dao->entity_table = 'civicrm_contribution_page';
966 $dao->entity_id = $this->_id;
967 $dao->find(TRUE);
968 $this->assign('contact_phone', $dao->premiums_contact_phone);
969 $this->assign('contact_email', $dao->premiums_contact_email);
970
971 //create Premium record
be2fb01f 972 $params = [
75637f22
EM
973 'product_id' => $premiumParams['selectProduct'],
974 'contribution_id' => $contribution->id,
6b409353 975 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ?? NULL,
75637f22
EM
976 'quantity' => 1,
977 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
978 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
be2fb01f 979 ];
75637f22
EM
980 if (!empty($premiumParams['selectProduct'])) {
981 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
982 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
983 $daoPremiumsProduct->premiums_id = $dao->id;
984 $daoPremiumsProduct->find(TRUE);
985 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
6a488035 986 }
75637f22
EM
987 //Fixed For CRM-3901
988 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
989 $daoContrProd->contribution_id = $contribution->id;
990 if ($daoContrProd->find(TRUE)) {
991 $params['id'] = $daoContrProd->id;
6a488035 992 }
6a488035 993
75637f22
EM
994 CRM_Contribute_BAO_Contribution::addPremium($params);
995 if ($productDAO->cost && !empty($params['financial_type_id'])) {
be2fb01f 996 $trxnParams = [
75637f22
EM
997 'cost' => $productDAO->cost,
998 'currency' => $productDAO->currency,
999 'financial_type_id' => $params['financial_type_id'],
1000 'contributionId' => $contribution->id,
be2fb01f 1001 ];
75637f22 1002 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
6a488035
TO
1003 }
1004 }
fb8d25da 1005 elseif ($selectProduct === 'no_thanks') {
75637f22
EM
1006 //Fixed For CRM-3901
1007 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1008 $daoContrProd->contribution_id = $contribution->id;
1009 if ($daoContrProd->find(TRUE)) {
1010 $daoContrProd->delete();
6a488035
TO
1011 }
1012 }
75637f22 1013 }
6a488035 1014
75637f22
EM
1015 /**
1016 * Process the contribution.
1017 *
1018 * @param CRM_Core_Form $form
1019 * @param array $params
1020 * @param array $result
f6261e9d 1021 * @param array $contributionParams
1022 * Parameters to be passed to contribution create action.
3febe800 1023 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1024 * passed consistently & 2) documenting them here.
1025 * - contact_id
1026 * - line_item
1027 * - is_test
1028 * - campaign_id
1029 * - contribution_page_id
1030 * - source
1031 * - payment_type_id
1032 * - thankyou_date (not all forms will set this)
1033 *
75637f22 1034 * @param CRM_Financial_DAO_FinancialType $financialType
75637f22 1035 * @param bool $online
3febe800 1036 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
75637f22 1037 *
75637f22
EM
1038 * @param int $billingLocationID
1039 * ID of billing location type.
10490499 1040 * @param bool $isRecur
1041 * Is this recurring?
75637f22
EM
1042 *
1043 * @return \CRM_Contribute_DAO_Contribution
12fde6ae 1044 *
1045 * @throws \CRM_Core_Exception
1046 * @throws \CiviCRM_API3_Exception
75637f22
EM
1047 */
1048 public static function processFormContribution(
1049 &$form,
1050 $params,
1051 $result,
f6261e9d 1052 $contributionParams,
75637f22 1053 $financialType,
75637f22 1054 $online,
449f4c90 1055 $billingLocationID,
1056 $isRecur
75637f22
EM
1057 ) {
1058 $transaction = new CRM_Core_Transaction();
f6261e9d 1059 $contactID = $contributionParams['contact_id'];
1060
75637f22 1061 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
91768280 1062 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
cbbbf0ef 1063 $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : $form->_values['pledge_id'] ?? NULL;
75637f22 1064 if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
09108d7d 1065 (!empty($params['is_pledge']) || $pledgeID)) {
75637f22 1066 $isPledge = TRUE;
6a488035
TO
1067 }
1068 else {
75637f22 1069 $isPledge = FALSE;
6a488035
TO
1070 }
1071
75637f22
EM
1072 // add these values for the recurringContrib function ,CRM-10188
1073 $params['financial_type_id'] = $financialType->id;
6a488035 1074
3febe800 1075 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
6a488035 1076
75637f22
EM
1077 //@todo - this is being set from the form to resolve CRM-10188 - an
1078 // eNotice caused by it not being set @ the front end
1079 // however, we then get it being over-written with null for backend contributions
1080 // a better fix would be to set the values in the respective forms rather than require
1081 // a function being shared by two forms to deal with their respective values
1082 // moving it to the BAO & not taking the $form as a param would make sense here.
1083 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1084 $params['is_email_receipt'] = $isEmailReceipt;
51e89def 1085 }
449f4c90 1086 $params['is_recur'] = $isRecur;
9c1bc317 1087 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ?? NULL;
449f4c90 1088 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
51e89def 1089
75637f22 1090 $now = date('YmdHis');
9c1bc317 1091 $receiptDate = $params['receipt_date'] ?? NULL;
75637f22
EM
1092 if ($isEmailReceipt) {
1093 $receiptDate = $now;
6a488035
TO
1094 }
1095
75637f22 1096 if (isset($params['amount'])) {
f6261e9d 1097 $contributionParams = array_merge(self::getContributionParams(
0ede7391 1098 $params, $financialType->id,
f6261e9d 1099 $result, $receiptDate,
1100 $recurringContributionID), $contributionParams
75637f22 1101 );
83644f47 1102 $contributionParams['non_deductible_amount'] = self::getNonDeductibleAmount($params, $financialType, $online, $form);
1103 $contributionParams['skipCleanMoney'] = TRUE;
1104 // @todo this is the wrong place for this - it should be done as close to form submission
1105 // as possible
1106 $contributionParams['total_amount'] = $params['amount'];
77beddbe 1107
f6261e9d 1108 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
6a488035 1109
aaffa79f 1110 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
9c1bc317 1111 $invoicing = $invoiceSettings['invoicing'] ?? NULL;
75637f22 1112 if ($invoicing) {
be2fb01f 1113 $dataArray = [];
f6261e9d 1114 // @todo - interrogate the line items passed in on the params array.
1115 // No reason to assume line items will be set on the form.
75637f22
EM
1116 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1117 foreach ($lineItemValue as $key => $value) {
1118 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1119 if (isset($dataArray[$value['tax_rate']])) {
2cfe2cf4 1120 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + $value['tax_amount'];
75637f22
EM
1121 }
1122 else {
2cfe2cf4 1123 $dataArray[$value['tax_rate']] = $value['tax_amount'];
75637f22
EM
1124 }
1125 }
6a488035
TO
1126 }
1127 }
75637f22
EM
1128 $smarty = CRM_Core_Smarty::singleton();
1129 $smarty->assign('dataArray', $dataArray);
79528215 1130 $smarty->assign('totalTaxAmount', $params['tax_amount'] ?? NULL);
75637f22 1131 }
6a488035 1132
75637f22
EM
1133 // lets store it in the form variable so postProcess hook can get to this and use it
1134 $form->_contributionID = $contribution->id;
1135 }
6a488035 1136
7a13735b 1137 // process soft credit / pcp params first
1138 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
75637f22 1139
7a13735b 1140 //CRM-13981, processing honor contact into soft-credit contribution
1141 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
75637f22 1142
75637f22 1143 if ($isPledge) {
356bfcaf 1144 $form = self::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
6a488035 1145 }
6a488035 1146
75637f22 1147 if ($online && $contribution) {
09108d7d 1148 CRM_Core_BAO_CustomValueTable::postProcess($params,
75637f22
EM
1149 'civicrm_contribution',
1150 $contribution->id,
1151 'Contribution'
1152 );
1153 }
1154 elseif ($contribution) {
1155 //handle custom data.
1156 $params['contribution_id'] = $contribution->id;
1157 if (!empty($params['custom']) &&
77beddbe 1158 is_array($params['custom'])
6a488035 1159 ) {
75637f22 1160 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
6a488035 1161 }
75637f22
EM
1162 }
1163 // Save note
1164 if ($contribution && !empty($params['contribution_note'])) {
be2fb01f 1165 $noteParams = [
75637f22
EM
1166 'entity_table' => 'civicrm_contribution',
1167 'note' => $params['contribution_note'],
1168 'entity_id' => $contribution->id,
1169 'contact_id' => $contribution->contact_id,
be2fb01f 1170 ];
75637f22 1171
be2fb01f 1172 CRM_Core_BAO_Note::add($noteParams, []);
cc789d46 1173 }
cc789d46 1174
75637f22
EM
1175 //create contribution activity w/ individual and target
1176 //activity w/ organisation contact id when onbelf, CRM-4027
d33f8fc4 1177 $actParams = [];
75637f22 1178 $targetContactID = NULL;
d33f8fc4
JP
1179 if (!empty($params['onbehalf_contact_id'])) {
1180 $actParams = [
1181 'source_contact_id' => $params['onbehalf_contact_id'],
1182 'on_behalf' => TRUE,
1183 ];
75637f22 1184 $targetContactID = $contribution->contact_id;
75637f22
EM
1185 }
1186
1187 // create an activity record
1188 if ($contribution) {
bf302610 1189 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
75637f22
EM
1190 }
1191
1192 $transaction->commit();
75637f22 1193 return $contribution;
6a488035
TO
1194 }
1195
1196 /**
75637f22 1197 * Create the recurring contribution record.
6a488035 1198 *
75637f22
EM
1199 * @param CRM_Core_Form $form
1200 * @param array $params
1201 * @param int $contactID
1202 * @param string $contributionType
75637f22 1203 *
449f4c90 1204 * @return int|null
6a488035 1205 */
449f4c90 1206 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
cde484fd 1207
449f4c90 1208 if (empty($params['is_recur'])) {
75637f22
EM
1209 return NULL;
1210 }
6a488035 1211
be2fb01f 1212 $recurParams = ['contact_id' => $contactID];
9c1bc317
CW
1213 $recurParams['amount'] = $params['amount'] ?? NULL;
1214 $recurParams['auto_renew'] = $params['auto_renew'] ?? NULL;
1215 $recurParams['frequency_unit'] = $params['frequency_unit'] ?? NULL;
1216 $recurParams['frequency_interval'] = $params['frequency_interval'] ?? NULL;
1217 $recurParams['installments'] = $params['installments'] ?? NULL;
1218 $recurParams['financial_type_id'] = $params['financial_type_id'] ?? NULL;
1219 $recurParams['currency'] = $params['currency'] ?? NULL;
f69a9ac3 1220 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
6a488035 1221
75637f22
EM
1222 // CRM-14354: For an auto-renewing membership with an additional contribution,
1223 // if separate payments is not enabled, make sure only the membership fee recurs
1224 if (!empty($form->_membershipBlock)
1225 && $form->_membershipBlock['is_separate_payment'] === '0'
1226 && isset($params['selectMembership'])
1227 && $form->_values['is_allow_other_amount'] == '1'
1228 // CRM-16331
1229 && !empty($form->_membershipTypeValues)
1230 && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])
1231 ) {
1232 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1233 }
6a488035 1234
75637f22
EM
1235 $recurParams['is_test'] = 0;
1236 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1237 (isset($form->_mode) && ($form->_mode == 'test'))
1238 ) {
1239 $recurParams['is_test'] = 1;
1240 }
6a488035 1241
75637f22
EM
1242 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1243 if (!empty($params['receive_date'])) {
12e53254 1244 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
75637f22 1245 }
9c1bc317 1246 $recurParams['invoice_id'] = $params['invoiceID'] ?? NULL;
75637f22 1247 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
9c1bc317 1248 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ?? NULL;
eba1a1d7 1249 $recurParams['is_email_receipt'] = (bool) ($params['is_email_receipt'] ?? FALSE);
75637f22
EM
1250 // we need to add a unique trxn_id to avoid a unique key error
1251 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
cbbbf0ef 1252 $recurParams['trxn_id'] = $params['trxn_id'] ?? $params['invoiceID'];
75637f22 1253 $recurParams['financial_type_id'] = $contributionType->id;
6a488035 1254
cbbbf0ef 1255 $campaignId = $params['campaign_id'] ?? $form->_values['campaign_id'] ?? NULL;
75637f22 1256 $recurParams['campaign_id'] = $campaignId;
75637f22
EM
1257 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1258 if (is_a($recurring, 'CRM_Core_Error')) {
1259 CRM_Core_Error::displaySessionError($recurring);
1260 $urlString = 'civicrm/contribute/transact';
1261 $urlParams = '_qf_Main_display=true';
1262 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1263 $urlString = 'civicrm/contact/view/contribution';
1264 $urlParams = "action=add&cid={$form->_contactID}";
1265 if ($form->_mode) {
1266 $urlParams .= "&mode={$form->_mode}";
1267 }
6a488035 1268 }
75637f22 1269 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
6a488035 1270 }
66c8ea62 1271 $form->_params['contributionRecurID'] = $recurring->id;
75637f22
EM
1272
1273 return $recurring->id;
6a488035
TO
1274 }
1275
1276 /**
75637f22 1277 * Add on behalf of organization and it's location.
cd6994fc 1278 *
75637f22
EM
1279 * This situation occurs when on behalf of is enabled for the contribution page and the person
1280 * signing up does so on behalf of an organization.
a1a94e61 1281 *
75637f22
EM
1282 * @param array $behalfOrganization
1283 * array of organization info.
1284 * @param int $contactID
1285 * individual contact id. One.
1286 * who is doing the process of signup / contribution.
9fc4e1d9 1287 *
75637f22
EM
1288 * @param array $values
1289 * form values array.
1290 * @param array $params
1291 * @param array $fields
1292 * Array of fields from the onbehalf profile relevant to the organization.
6a488035 1293 */
75637f22 1294 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
33260076 1295 $isNotCurrentEmployer = FALSE;
be2fb01f 1296 $dupeIDs = [];
75637f22 1297 $orgID = NULL;
6cc679d2 1298 if (!empty($behalfOrganization['organization_id'])) {
75637f22
EM
1299 $orgID = $behalfOrganization['organization_id'];
1300 unset($behalfOrganization['organization_id']);
33260076 1301 }
1302 // create employer relationship with $contactID only when new organization is there
1303 // else retain the existing relationship
1304 else {
33260076 1305 $isNotCurrentEmployer = TRUE;
bb06e9ed 1306 }
6a488035 1307
75637f22
EM
1308 if (!$orgID) {
1309 // check if matching organization contact exists
be2fb01f 1310 $dupeIDs = CRM_Contact_BAO_Contact::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
6a488035 1311
75637f22
EM
1312 // CRM-6243 says to pick the first org even if more than one match
1313 if (count($dupeIDs) >= 1) {
75c07fde 1314 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
75637f22
EM
1315 // don't allow name edit
1316 unset($behalfOrganization['organization_name']);
6a488035
TO
1317 }
1318 }
1319 else {
75637f22
EM
1320 // if found permissioned related organization, allow location edit
1321 $behalfOrganization['contact_id'] = $orgID;
1322 // don't allow name edit
1323 unset($behalfOrganization['organization_name']);
6a488035
TO
1324 }
1325
75637f22
EM
1326 // handling for image url
1327 if (!empty($behalfOrganization['image_URL'])) {
1328 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
6a488035
TO
1329 }
1330
75637f22 1331 // create organization, add location
e4addeb2 1332 $behalfOrganization['contact_type'] = 'Organization';
75637f22
EM
1333 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1334 NULL, NULL, 'Organization'
1335 );
1336 // create relationship
33260076 1337 if ($isNotCurrentEmployer) {
e4addeb2
JG
1338 try {
1339 \Civi\Api4\Relationship::create(FALSE)
1340 ->addValue('contact_id_a', $contactID)
1341 ->addValue('contact_id_b', $orgID)
1342 ->addValue('relationship_type_id', CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'))
1343 ->addValue('is_permission_a_b:name', 'View and update')
1344 ->execute();
1345 }
1346 catch (CRM_Core_Exception $e) {
1347 // Ignore if duplicate relationship.
1348 if ($e->getMessage() !== 'Duplicate Relationship') {
1349 throw $e;
1350 }
1351 }
33260076 1352 }
1f1740fe 1353
75637f22
EM
1354 // if multiple match - send a duplicate alert
1355 if ($dupeIDs && (count($dupeIDs) > 1)) {
1356 $values['onbehalf_dupe_alert'] = 1;
1357 // required for IPN
1358 $params['onbehalf_dupe_alert'] = 1;
6a488035 1359 }
cde484fd 1360
75637f22
EM
1361 // make sure organization-contact-id is considered for recording
1362 // contribution/membership etc..
1363 if ($contactID != $orgID) {
1364 // take a note of contact-id, so we can send the
1365 // receipt to individual contact as well.
6a488035 1366
75637f22
EM
1367 // required for mailing/template display ..etc
1368 $values['related_contact'] = $contactID;
6a488035 1369
0462a5b2 1370 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1371 $params['onbehalf_contact_id'] = $contactID;
1372
75637f22
EM
1373 //make this employee of relationship as current
1374 //employer / employee relationship, CRM-3532
33260076 1375 if ($isNotCurrentEmployer &&
75637f22
EM
1376 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1377 ) {
33260076 1378 $isNotCurrentEmployer = FALSE;
6a488035 1379 }
6a488035 1380
33260076 1381 if (!$isNotCurrentEmployer && $orgID) {
75637f22
EM
1382 //build current employer params
1383 $currentEmpParams[$contactID] = $orgID;
1384 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
6a488035 1385 }
6a488035 1386
75637f22
EM
1387 // contribution / signup will be done using this
1388 // organization id.
1389 $contactID = $orgID;
6a488035 1390 }
75637f22
EM
1391 }
1392
6a488035 1393 /**
75637f22 1394 * Function used to send notification mail to pcp owner.
6a488035 1395 *
75637f22 1396 * This is used by contribution and also event PCPs.
03110609 1397 *
75637f22 1398 * @param object $contribution
26f76772 1399 * @param array $contributionSoft
75637f22 1400 * Contribution object.
26f76772 1401 *
1402 * @throws \API_Exception
1403 * @throws \CRM_Core_Exception
12f92dbd 1404 */
26f76772 1405 public static function pcpNotifyOwner($contribution, array $contributionSoft) {
1406 $params = ['id' => $contributionSoft['pcp_id']];
5fe87df6
N
1407 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1408 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
ed71bbca 1409 $ownerNotifyOption = CRM_Core_PseudoConstant::getName('CRM_PCP_DAO_PCPBlock', 'owner_notify_id', $ownerNotifyID);
5fe87df6 1410
ed71bbca 1411 if ($ownerNotifyOption != 'no_notifications' &&
1412 (($ownerNotifyOption == 'owner_chooses' &&
26f76772 1413 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft['pcp_id'], 'is_notify')) ||
ed71bbca 1414 $ownerNotifyOption == 'all_owners')) {
5fe87df6 1415 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
26f76772 1416 "reset=1&id={$contributionSoft['pcp_id']}",
5fe87df6
N
1417 TRUE, NULL, FALSE, TRUE
1418 );
12f92dbd 1419 // set email in the template here
5fe87df6 1420
b576d770 1421 if (CRM_Core_BAO_LocationType::getBilling()) {
fb8d25da 1422 [$donorName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id,
b576d770 1423 FALSE, CRM_Core_BAO_LocationType::getBilling());
5fe87df6
N
1424 }
1425 // get primary location email if no email exist( for billing location).
1426 if (!$email) {
fb8d25da 1427 [$donorName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
5fe87df6 1428 }
26f76772 1429 [$ownerName, $ownerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft['contact_id']);
be2fb01f 1430 $tplParams = [
5fe87df6 1431 'page_title' => $pcpInfo['title'],
12f92dbd 1432 'receive_date' => $contribution->receive_date,
26f76772 1433 'total_amount' => $contributionSoft['amount'],
12f92dbd 1434 'donors_display_name' => $donorName,
5fe87df6
N
1435 'donors_email' => $email,
1436 'pcpInfoURL' => $pcpInfoURL,
26f76772 1437 'is_honor_roll_enabled' => $contributionSoft['pcp_display_in_roll'],
1438 'currency' => $contributionSoft['currency'],
be2fb01f 1439 ];
12f92dbd 1440 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
be2fb01f 1441 $sendTemplateParams = [
12f92dbd
N
1442 'groupName' => 'msg_tpl_workflow_contribution',
1443 'valueName' => 'pcp_owner_notify',
26f76772 1444 'contactId' => $contributionSoft['contact_id'],
5fe87df6
N
1445 'toEmail' => $ownerEmail,
1446 'toName' => $ownerName,
12f92dbd
N
1447 'from' => "$domainValues[0] <$domainValues[1]>",
1448 'tplParams' => $tplParams,
1449 'PDFFilename' => 'receipt.pdf',
be2fb01f 1450 ];
12f92dbd 1451 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1452 }
1453 }
1454
1455 /**
5e4f7f74
EM
1456 * Function used to se pcp related defaults / params.
1457 *
1458 * This is used by contribution and also event PCPs
6a488035 1459 *
014c4014
TO
1460 * @param CRM_Core_Form $page
1461 * Form object.
1462 * @param array $params
6a488035 1463 *
cd6994fc 1464 * @return array
6a488035 1465 */
26f76772 1466 public static function processPcp(&$page, $params): array {
547206bc 1467 $params['pcp_made_through_id'] = $page->_pcpId;
6a488035 1468 $page->assign('pcpBlock', TRUE);
8cc574cf 1469 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
6a488035
TO
1470 $params['pcp_roll_nickname'] = ts('Anonymous');
1471 $params['pcp_is_anonymous'] = 1;
1472 }
1473 else {
1474 $params['pcp_is_anonymous'] = 0;
1475 }
be2fb01f 1476 foreach ([
1330f57a
SL
1477 'pcp_display_in_roll',
1478 'pcp_is_anonymous',
1479 'pcp_roll_nickname',
1480 'pcp_personal_note',
1481 ] as $val) {
a7488080 1482 if (!empty($params[$val])) {
6a488035
TO
1483 $page->assign($val, $params[$val]);
1484 }
1485 }
1486
1487 return $params;
1488 }
705b4205
EM
1489
1490 /**
5e4f7f74
EM
1491 * Process membership.
1492 *
5624f515 1493 * @param array $membershipParams
014c4014 1494 * @param int $contactID
5624f515
EM
1495 * @param array $customFieldsFormatted
1496 * @param array $fieldTypes
1497 * @param array $premiumParams
014c4014
TO
1498 * @param array $membershipLineItems
1499 * Line items specifically relating to memberships.
705b4205 1500 */
4b6c8c1e 1501 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
26f76772 1502 $membershipLineItems): void {
8bc79dfc 1503
4b6c8c1e 1504 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1505 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
be2fb01f 1506 $membershipType = empty($membershipTypes) ? [] : reset($membershipTypes);
5624f515 1507
cbbbf0ef 1508 $this->assign('membership_name', $membershipType['name']);
9c1bc317 1509 $this->_values['membership_name'] = $membershipType['name'] ?? NULL;
7c113627 1510
4b6c8c1e 1511 $isPaidMembership = FALSE;
1512 if ($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1513 //amount must be greater than zero for
1514 //adding contribution record to contribution table.
1515 //this condition arises when separate membership payment is
1516 //enabled and contribution amount is not selected. fix for CRM-3010
1517 $isPaidMembership = TRUE;
1518 }
1519 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
7c113627 1520
4b6c8c1e 1521 if ($this->_values['amount_block_is_active']) {
1522 $financialTypeID = $this->_values['financial_type_id'];
705b4205 1523 }
4b6c8c1e 1524 else {
cbbbf0ef 1525 $financialTypeID = $membershipType['financial_type_id'] ?? $membershipParams['financial_type_id'] ?? NULL;
705b4205 1526 }
4b6c8c1e 1527
f3acfdd9 1528 if (!empty($this->_params['membership_source'])) {
4b6c8c1e 1529 $membershipParams['contribution_source'] = $this->_params['membership_source'];
1530 }
1531
1532 $this->postProcessMembership($membershipParams, $contactID,
1533 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $financialTypeID,
5b9d3ce8 1534 $membershipLineItems);
4b6c8c1e 1535
1536 $this->assign('membership_assign', TRUE);
1537 $this->set('membershipTypeID', $membershipParams['selectMembership']);
705b4205 1538 }
fb49fa48 1539
8bc79dfc 1540 /**
668ddfc2
EM
1541 * Process the Memberships.
1542 *
1543 * @param array $membershipParams
1544 * Array of membership fields.
1545 * @param int $contactID
1546 * Contact id.
1547 * @param CRM_Contribute_Form_Contribution_Confirm $form
1548 * Confirmation form object.
1549 *
1550 * @param array $premiumParams
1551 * @param null $customFieldsFormatted
1552 * @param null $includeFieldTypes
1553 *
1554 * @param array $membershipDetails
1555 *
1556 * @param array $membershipTypeIDs
1557 *
1558 * @param bool $isPaidMembership
1559 * @param array $membershipID
1560 *
1561 * @param bool $isProcessSeparateMembershipTransaction
1562 *
1563 * @param int $financialTypeID
f2bca231 1564 * @param array $unprocessedLineItems
1565 * Line items for payment options chosen on the form.
668ddfc2
EM
1566 *
1567 * @throws \CRM_Core_Exception
5b9d3ce8
MWMC
1568 * @throws \CiviCRM_API3_Exception
1569 * @throws \Civi\Payment\Exception\PaymentProcessorException
668ddfc2
EM
1570 */
1571 protected function postProcessMembership(
1572 $membershipParams, $contactID, &$form, $premiumParams,
1573 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
5b9d3ce8 1574 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
f2bca231 1575
82583880 1576 $membershipContribution = NULL;
cbbbf0ef 1577 $isTest = $membershipParams['is_test'] ?? FALSE;
be2fb01f 1578 $errors = $paymentResults = [];
858f7096 1579 $form->_values['isMembership'] = TRUE;
cbbbf0ef 1580 $isRecurForFirstTransaction = $form->_params['is_recur'] ?? $membershipParams['is_recur'] ?? NULL;
f2bca231 1581
858f7096 1582 $totalAmount = $membershipParams['amount'];
449f4c90 1583
668ddfc2
EM
1584 if ($isPaidMembership) {
1585 if ($isProcessSeparateMembershipTransaction) {
1586 // If we have 2 transactions only one can use the invoice id.
1587 $membershipParams['invoiceID'] .= '-2';
449f4c90 1588 if (!empty($membershipParams['auto_renew'])) {
1589 $isRecurForFirstTransaction = FALSE;
1590 }
668ddfc2
EM
1591 }
1592
417c6834 1593 if (!$isProcessSeparateMembershipTransaction) {
f2bca231 1594 // Skip line items in the contribution processing transaction.
1595 // We will create them with the membership for proper linking.
417c6834 1596 $membershipParams['skipLineItem'] = 1;
1597 }
8e8d287f 1598 else {
1599 $membershipParams['total_amount'] = $totalAmount;
f2bca231 1600 $membershipParams['skipLineItem'] = 0;
8e8d287f 1601 CRM_Price_BAO_LineItem::getLineItemArray($membershipParams);
1602
1603 }
1a3545fa 1604 $paymentResult = $form->processConfirm(
f2bca231 1605 $membershipParams,
5fb28746 1606 $contactID,
668ddfc2 1607 $financialTypeID,
449f4c90 1608 $isTest,
1609 $isRecurForFirstTransaction
668ddfc2 1610 );
82583880 1611 if (!empty($paymentResult['contribution'])) {
be2fb01f 1612 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentResult];
5fb28746 1613 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
668ddfc2
EM
1614 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1615 $membershipContribution = $paymentResult['contribution'];
1616 // Save the contribution ID so that I can be used in email receipts
1617 // For example, if you need to generate a tax receipt for the donation only.
1618 $form->_values['contribution_other_id'] = $membershipContribution->id;
1619 }
1620 }
1621
1622 if ($isProcessSeparateMembershipTransaction) {
1623 try {
f2bca231 1624 $form->_lineItem = $unprocessedLineItems;
668ddfc2
EM
1625 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1626 unset($membershipParams['is_recur']);
1627 }
fb8d25da 1628 [$membershipContribution, $secondPaymentResult] = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, ['skipLineItem' => 1]),
cbbbf0ef 1629 $isTest, $unprocessedLineItems, $membershipDetails['minimum_fee'] ?? 0, $membershipDetails['financial_type_id'] ?? NULL);
be2fb01f 1630 $paymentResults[] = ['contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult];
d275cdb2 1631 $totalAmount = $membershipContribution->total_amount;
668ddfc2
EM
1632 }
1633 catch (CRM_Core_Exception $e) {
1634 $errors[2] = $e->getMessage();
1635 $membershipContribution = NULL;
1636 }
1637 }
1638
1639 $membership = NULL;
1640 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1641 $membershipContributionID = $membershipContribution->id;
1642 }
1643
1644 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1645 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1646 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1647 }
1648 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1649 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
cbbbf0ef 1650 $typesTerms = $membershipParams['types_terms'] ?? [];
65e172a3 1651
be2fb01f 1652 $membershipLines = $nonMembershipLines = [];
65e172a3 1653 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1654 foreach ($lines as $line) {
1655 if (!empty($line['membership_type_id'])) {
1656 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1657 }
1658 }
1659 }
1660
1661 $i = 1;
be2fb01f 1662 $form->_params['createdMembershipIDs'] = [];
668ddfc2 1663 foreach ($membershipTypeIDs as $memType) {
be2fb01f 1664 $membershipLineItems = [];
65e172a3 1665 if ($i < count($membershipTypeIDs)) {
1666 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1667 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1668 }
1669 else {
1670 $membershipLineItems = $unprocessedLineItems;
1671 }
1672 $i++;
cbbbf0ef 1673 $numTerms = $typesTerms[$memType] ?? 1;
77c21b32 1674 $contributionRecurID = $form->_params['contributionRecurID'] ?? NULL;
668ddfc2
EM
1675
1676 $membershipSource = NULL;
1677 if (!empty($form->_params['membership_source'])) {
1678 $membershipSource = $form->_params['membership_source'];
1679 }
6489e3de
SL
1680 elseif ((isset($form->_values['title']) && !empty($form->_values['title'])) || (isset($form->_values['frontend_title']) && !empty($form->_values['frontend_title']))) {
1681 $title = !empty($form->_values['frontend_title']) ? $form->_values['frontend_title'] : $form->_values['title'];
1682 $membershipSource = ts('Online Contribution:') . ' ' . $title;
668ddfc2
EM
1683 }
1684 $isPayLater = NULL;
1685 if (isset($form->_params)) {
9c1bc317 1686 $isPayLater = $form->_params['is_pay_later'] ?? NULL;
668ddfc2 1687 }
5fbbde1f 1688 $memParams = [
1689 'campaign_id' => $form->_params['campaign_id'] ?? ($form->_values['campaign_id'] ?? NULL),
1690 ];
668ddfc2 1691
5b9d3ce8
MWMC
1692 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1693 if (!empty($membershipContribution)) {
3ec3dcbe 1694 $pending = $membershipContribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
5b9d3ce8
MWMC
1695 }
1696 else {
cbbbf0ef
MW
1697 // The concept of contributeMode is deprecated.
1698 // the is_monetary concept probably should be too as it can be calculated from
1699 // the existence of 'amount' & seems fragile.
1700 if (((isset($this->_contributeMode)) || !empty($this->_params['is_pay_later'])
1701 ) &&
1702 (($this->_values['is_monetary'] && $this->_amount > 0.0))
1703 ) {
1704 $pending = TRUE;
1705 }
1706 $pending = FALSE;
5b9d3ce8 1707 }
cbbbf0ef 1708
fb8d25da 1709 [$membership, $renewalMode, $dates] = CRM_Member_BAO_Membership::processMembership(
668ddfc2 1710 $contactID, $memType, $isTest,
cbbbf0ef 1711 date('YmdHis'), $membershipParams['cms_contactID'] ?? NULL,
668ddfc2
EM
1712 $customFieldsFormatted,
1713 $numTerms, $membershipID, $pending,
5fbbde1f 1714 $contributionRecurID, $membershipSource, $isPayLater, $memParams, [], $membershipContribution,
65e172a3 1715 $membershipLineItems
668ddfc2 1716 );
bd53b1b9 1717
668ddfc2
EM
1718 $form->set('renewal_mode', $renewalMode);
1719 if (!empty($dates)) {
1fc22ffa 1720 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
1721 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
668ddfc2
EM
1722 }
1723
1724 if (!empty($membershipContribution)) {
c9cc6e3a
MWMC
1725 // Next line is probably redundant. Checks prevent it happening twice.
1726 $membershipPaymentParams = [
1727 'membership_id' => $membership->id,
1728 'membership_type_id' => $membership->membership_type_id,
1729 'contribution_id' => $membershipContribution->id,
1730 ];
1731 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
668ddfc2 1732 }
040728f5
AF
1733 if ($membership) {
1734 CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $membership->id, 'Membership');
1735 $form->_params['createdMembershipIDs'][] = $membership->id;
1736 $form->_params['membershipID'] = $membership->id;
1737
1738 //CRM-15232: Check if membership is created and on the basis of it use
1739 //membership receipt template to send payment receipt
1740 $form->_values['isMembership'] = TRUE;
1741 }
668ddfc2
EM
1742 }
1743 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1744 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
e894942a
WA
1745 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id == $priceFieldOp['membership_type_id']) {
1746 $membershipOb = $membership;
56f54f02 1747 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::formatDateOnlyLong($membershipOb->start_date) : '-';
1748 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::formatDateOnlyLong($membershipOb->end_date) : '-';
668ddfc2
EM
1749 }
1750 else {
1751 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1752 }
1753 }
1754 $form->_values['lineItem'] = $form->_lineItem;
1755 $form->assign('lineItem', $form->_lineItem);
1756 }
1757 }
1758
1759 if (!empty($errors)) {
1760 $message = $this->compileErrorMessage($errors);
1761 throw new CRM_Core_Exception($message);
1762 }
28da8ecd 1763
82583880
EM
1764 if (isset($membershipContributionID)) {
1765 $form->_values['contribution_id'] = $membershipContributionID;
1766 }
a506739a 1767
1fc22ffa 1768 if (empty($form->_params['is_pay_later']) && $form->_paymentProcessor) {
a506739a 1769 // the is_monetary concept probably should be deprecated as it can be calculated from
1770 // the existence of 'amount' & seems fragile.
668ddfc2
EM
1771 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1772 // call postProcess hook before leaving
1773 $form->postProcessHook();
668ddfc2 1774 }
a506739a 1775
82583880 1776 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
fe3dbce1 1777 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1778 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1779 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
be2fb01f 1780 $paymentParams = array_merge($form->_params, ['contributionID' => $form->_values['contribution_other_id']]);
b43ed44b
PN
1781
1782 // CRM-19792 : set necessary fields for payment processor
1783 CRM_Core_Payment_Form::mapParams($form->_bltID, $paymentParams, $paymentParams, TRUE);
1784
15816cb4
AS
1785 // If this is a single membership-related contribution, it won't have
1786 // be performed yet, so do it now.
1787 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1788 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
be2fb01f 1789 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult];
15816cb4 1790 }
668ddfc2
EM
1791 // Do not send an email if Recurring transaction is done via Direct Mode
1792 // Email will we sent when the IPN is received.
63137f3a 1793 foreach ($paymentResults as $result) {
7c864699
TL
1794 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1795 if ($result['contribution_id']) {
1796 $this->completeTransaction($result['result'], $result['contribution_id']);
1797 }
63137f3a 1798 }
668ddfc2
EM
1799 return;
1800 }
1801
1fc22ffa 1802 $emailValues = array_merge($membershipParams, $form->_values);
1803 $emailValues['membership_assign'] = 1;
05d09dc4
JP
1804 $emailValues['useForMember'] = !empty($form->_useForMember);
1805
858f7096 1806 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1807 if ($totalAmount == 0) {
1808 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1809 $emailValues['useForMember'] = 0;
858f7096 1810 $emailValues['amount'] = 0;
036c6315 1811
1812 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1813 // also it reset any payment processor selection result into pending free membership
1814 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
bd53b1b9 1815 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
18135422 1816 if (empty($form->_paymentProcessor)) {
1817 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
cbbbf0ef 1818 $paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_values['payment_processor'] ?? NULL);
036c6315 1819 $this->_paymentProcessor['id'] = $paymentProcessorIDs[0];
1820 }
be2fb01f 1821 $result = ['payment_status_id' => 1, 'contribution' => $membershipContribution];
036c6315 1822 $this->completeTransaction($result, $result['contribution']->id);
1823 }
1e584dec
JP
1824 // return as completeTransaction() already sends the receipt mail.
1825 return;
858f7096 1826 }
1fc22ffa 1827
668ddfc2 1828 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
858f7096 1829 $emailValues,
668ddfc2
EM
1830 $isTest, FALSE,
1831 $includeFieldTypes
1832 );
1833 }
1834
1835 /**
1836 * Turn array of errors into message string.
1837 *
1838 * @param array $errors
1839 *
1840 * @return string
1841 */
1842 protected function compileErrorMessage($errors) {
1843 foreach ($errors as $error) {
1844 if (is_string($error)) {
1845 $message[] = $error;
1846 }
1847 }
1848 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1849 }
1850
1851 /**
1852 * Where a second separate financial transaction is supported we will process it here.
1853 *
1854 * @param int $contactID
1855 * @param CRM_Contribute_Form_Contribution_Confirm $form
1856 * @param array $tempParams
1857 * @param bool $isTest
1858 * @param array $lineItems
1859 * @param $minimumFee
1860 * @param int $financialTypeID
1861 *
1862 * @throws CRM_Core_Exception
1863 * @throws Exception
1864 * @return CRM_Contribute_BAO_Contribution
1865 */
1866 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1867 $financialTypeID) {
1868 $financialType = new CRM_Financial_DAO_FinancialType();
1869 $financialType->id = $financialTypeID;
1870 $financialType->find(TRUE);
1871 $tempParams['amount'] = $minimumFee;
1872 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
9c1bc317 1873 $isRecur = $tempParams['is_recur'] ?? NULL;
668ddfc2 1874
668ddfc2
EM
1875 //assign receive date when separate membership payment
1876 //and contribution amount not selected.
1877 if ($form->_amount == 0) {
1878 $now = date('YmdHis');
1879 $form->_params['receive_date'] = $now;
1880 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
1881 $form->set('params', $form->_params);
1882 $form->assign('receive_date', $receiveDate);
1883 }
1884
668ddfc2 1885 $form->set('membership_amount', $minimumFee);
668ddfc2
EM
1886 $form->assign('membership_amount', $minimumFee);
1887
668ddfc2
EM
1888 //set this variable as we are not creating pledge for
1889 //separate membership payment contribution.
1890 //so for differentiating membership contribution from
1891 //main contribution.
1892 $form->_params['separate_membership_payment'] = 1;
be2fb01f 1893 $contributionParams = [
3febe800 1894 'contact_id' => $contactID,
1895 'line_item' => $lineItems,
1896 'is_test' => $isTest,
cbbbf0ef 1897 'campaign_id' => $tempParams['campaign_id'] ?? $form->_values['campaign_id'] ?? NULL,
3febe800 1898 'contribution_page_id' => $form->_id,
cbbbf0ef 1899 'source' => $tempParams['source'] ?? $tempParams['description'] ?? NULL,
be2fb01f 1900 ];
3febe800 1901 $isMonetary = !empty($form->_values['is_monetary']);
1902 if ($isMonetary) {
1903 if (empty($paymentParams['is_pay_later'])) {
f3a63d1e 1904 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
3febe800 1905 }
1906 }
b43ed44b
PN
1907
1908 // CRM-19792 : set necessary fields for payment processor
1909 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $tempParams, TRUE);
1910
668ddfc2
EM
1911 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
1912 $tempParams,
0193ebdb 1913 $tempParams,
3febe800 1914 $contributionParams,
668ddfc2 1915 $financialType,
668ddfc2 1916 TRUE,
449f4c90 1917 $form->_bltID,
1918 $isRecur
668ddfc2 1919 );
0193ebdb 1920
be2fb01f 1921 $result = [];
15816cb4 1922
7f5ae3a0
AS
1923 // We're not processing the line item here because we are processing a membership.
1924 // To ensure processing of the correct parameters, replace relevant parameters
1925 // in $tempParams with those in $membershipContribution.
1926 $tempParams['amount_level'] = $membershipContribution->amount_level;
1927 $tempParams['total_amount'] = $membershipContribution->total_amount;
1928 $tempParams['tax_amount'] = $membershipContribution->tax_amount;
1929 $tempParams['contactID'] = $membershipContribution->contact_id;
1930 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id;
1931 $tempParams['invoiceID'] = $membershipContribution->invoice_id;
1932 $tempParams['trxn_id'] = $membershipContribution->trxn_id;
1933 $tempParams['contributionID'] = $membershipContribution->id;
15816cb4 1934
0193ebdb 1935 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
1936 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1937 // now we compensate here.
1938 if (empty($form->_paymentProcessor['object'])) {
1939 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1940 }
1941 else {
1942 $payment = $form->_paymentProcessor['object'];
1943 }
1944 $result = $payment->doPayment($tempParams, 'contribute');
1945 $form->set('membership_trx_id', $result['trxn_id']);
1946 $form->assign('membership_trx_id', $result['trxn_id']);
0193ebdb 1947 }
1948
be2fb01f 1949 return [$membershipContribution, $result];
668ddfc2
EM
1950 }
1951
fb49fa48 1952 /**
5e4f7f74 1953 * Are we going to do 2 financial transactions.
fb49fa48 1954 *
5e4f7f74
EM
1955 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1956 * contribution
81355da3 1957 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
fb49fa48 1958 *
014c4014 1959 * @param int $formID
fb49fa48
EM
1960 * @param bool $amountBlockActiveOnForm
1961 *
1962 * @return bool
1963 */
1964 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1965 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1966 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1967 return TRUE;
1968 }
1969 return FALSE;
1970 }
df6c4f28
EM
1971
1972 /**
5e4f7f74
EM
1973 * This function sets the fields.
1974 *
df6c4f28
EM
1975 * - $this->_params['amount_level']
1976 * - $this->_params['selectMembership']
1977 * And under certain circumstances sets
1978 * $this->_params['amount'] = null;
1979 *
100fef9d 1980 * @param int $priceSetID
df6c4f28
EM
1981 */
1982 public function setFormAmountFields($priceSetID) {
1983 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1984 $priceField = new CRM_Price_DAO_PriceField();
1985 $priceField->price_set_id = $priceSetID;
1986 $priceField->orderBy('weight');
1987 $priceField->find();
06b4ee3e 1988 $paramWeDoNotUnderstand = NULL;
df6c4f28
EM
1989
1990 while ($priceField->fetch()) {
df6c4f28
EM
1991 if ($priceField->name == "contribution_amount") {
1992 $paramWeDoNotUnderstand = $priceField->id;
1993 }
1994 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1995 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
c039f658 1996 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1997 // function to get correct amount level consistently. Remove setting of the amount level in
1998 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1999 // to cover all variants.
df6c4f28
EM
2000 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
2001 $this->_params["price_{$priceField->id}"], 'label');
2002 }
2003 if ($priceField->name == "membership_amount") {
2004 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
2005 $this->_params["price_{$priceField->id}"], 'membership_type_id');
2006 }
5e4f7f74
EM
2007 }
2008 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
2009 // as membership amount.
df6c4f28
EM
2010 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
2011 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
2012 // so we should merge them together
2013 // the quick config seems like a red-herring - if this is about a separate membership payment then there
f64a217a 2014 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
df6c4f28 2015 elseif (
b99f3e96 2016 !empty($this->_membershipBlock['is_separate_payment'])
df6c4f28
EM
2017 && !empty($this->_values['fee'][$priceField->id])
2018 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
cbbbf0ef 2019 && ($this->_params["price_{$paramWeDoNotUnderstand}"] ?? NULL) < 1
df6c4f28
EM
2020 && empty($this->_params["price_{$priceField->id}"])
2021 ) {
a13f3d8c 2022 $this->_params['amount'] = NULL;
df6c4f28
EM
2023 }
2024
2025 // Fix for CRM-14375 - If we are using separate payments and "no
2026 // thank you" is selected for the additional contribution, set
2027 // contribution amount to be null, so that it will not show
2028 // contribution amount same as membership amount.
2029 //@todo - merge with section above
32c3b33f 2030 if (!empty($this->_membershipBlock['is_separate_payment'])
3c0201c9 2031 && !empty($this->_values['fee'][$priceField->id])
cbbbf0ef
MW
2032 && ($this->_values['fee'][$priceField->id]['name'] ?? NULL) == 'contribution_amount'
2033 && ($this->_params["price_{$priceField->id}"] ?? NULL) == '-1'
df6c4f28 2034 ) {
a13f3d8c 2035 $this->_params['amount'] = NULL;
df6c4f28
EM
2036 }
2037 }
2038 }
be26f3e0 2039
03110609 2040 /**
5e4f7f74
EM
2041 * Submit function.
2042 *
03110609
EM
2043 * @param array $params
2044 *
2045 * @throws CiviCRM_API3_Exception
2046 */
00be9182 2047 public static function submit($params) {
be26f3e0
EM
2048 $form = new CRM_Contribute_Form_Contribution_Confirm();
2049 $form->_id = $params['id'];
75637f22 2050
f64a217a
EM
2051 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
2052 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
be26f3e0
EM
2053 //this way the mocked up controller ignores the session stuff
2054 $_SERVER['REQUEST_METHOD'] = 'GET';
2055 $form->controller = new CRM_Contribute_Controller_Contribution();
2056 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
ec57bf87 2057
2058 // We want to move away from passing in amount as it is calculated by the actually-submitted params.
58315149 2059 if ($form->getMainContributionAmount($params)) {
2060 $params['amount'] = $form->getMainContributionAmount($params);
2061 }
be26f3e0 2062 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
58315149 2063
2064 $order = new CRM_Financial_BAO_Order();
2065 $order->setPriceSelectionFromUnfilteredInput($params);
2066 if (isset($params['amount'])) {
2067 // @todo deprecate receiving amount, calculate on the form.
2068 $order->setOverrideTotalAmount($params['amount']);
2069 }
2070 $amount = $order->getTotalAmount();
2071 $form->_amount = $params['amount'] = $form->_params['amount'] = $params['amount'] ?? $amount;
870156d6 2072 // hack these in for test support.
2073 $form->_fields['billing_first_name'] = 1;
2074 $form->_fields['billing_last_name'] = 1;
dccd9f4f 2075 // CRM-18854 - Set form values to allow pledge to be created for api test.
de6c59ca 2076 if (!empty($params['pledge_block_id'])) {
9c1bc317 2077 $form->_values['pledge_id'] = $params['pledge_id'] ?? NULL;
dccd9f4f
ERL
2078 $form->_values['pledge_block_id'] = $params['pledge_block_id'];
2079 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($params['id']);
2080 $form->_values['max_reminders'] = $pledgeBlock['max_reminders'];
2081 $form->_values['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
2082 $form->_values['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
2083 $form->_values['is_email_receipt'] = FALSE;
2084 }
be26f3e0
EM
2085 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
2086 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
f64a217a
EM
2087 $priceSetFields = reset($priceFields);
2088 $form->_values['fee'] = $priceSetFields['fields'];
5624f515 2089 $form->_priceSetId = $priceSetID;
be26f3e0 2090 $form->setFormAmountFields($priceSetID);
be2fb01f 2091 $capabilities = [];
18135422 2092 if ($form->_mode) {
2093 $capabilities[] = (ucfirst($form->_mode) . 'Mode');
2094 }
2095 $form->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
77c21b32 2096 $form->_params['payment_processor_id'] = $params['payment_processor_id'] ?? 0;
04b24bb5 2097 if ($form->_params['payment_processor_id'] !== '') {
2098 // It can be blank with a $0 transaction - then no processor needs to be selected
2099 $form->_paymentProcessor = $form->_paymentProcessors[$form->_params['payment_processor_id']];
2100 }
e02d7e96 2101 if (!empty($params['payment_processor_id'])) {
0f2b049e 2102 // The concept of contributeMode is deprecated as is the billing_mode concept.
a13f3d8c 2103 if ($form->_paymentProcessor['billing_mode'] == 1) {
e6fa4056
EM
2104 $form->_contributeMode = 'direct';
2105 }
2106 else {
2107 $form->_contributeMode = 'notify';
2108 }
d25e4224 2109 }
65e172a3 2110
ed781038
JP
2111 if (!empty($params['useForMember'])) {
2112 $form->set('useForMember', 1);
2113 $form->_useForMember = 1;
2114 }
be26f3e0 2115 $priceFields = $priceFields[$priceSetID]['fields'];
be2fb01f 2116 $lineItems = [];
bdcbbfea 2117 $form->processAmountAndGetAutoRenew($priceFields, $paramsProcessedForForm, $lineItems, $priceSetID);
be2fb01f
CW
2118 $form->_lineItem = [$priceSetID => $lineItems];
2119 $membershipPriceFieldIDs = [];
65e172a3 2120 foreach ((array) $lineItems as $lineItem) {
2121 if (!empty($lineItem['membership_type_id'])) {
2122 $form->set('useForMember', 1);
2123 $form->_useForMember = 1;
2124 $membershipPriceFieldIDs['id'] = $priceSetID;
2125 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
2126 }
2127 }
2128 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
35bdddf0 2129 $form->setRecurringMembershipParams();
cbbbf0ef 2130 $form->processFormSubmission($params['contact_id'] ?? NULL);
be26f3e0
EM
2131 }
2132
2133 /**
ceb9fecb
EM
2134 * Helper function for static submit function.
2135 *
2136 * Set relevant params - help us to build up an array that we can pass in.
5e4f7f74 2137 *
100fef9d 2138 * @param int $id
be26f3e0
EM
2139 * @param array $params
2140 *
2141 * @return array
2142 * @throws CiviCRM_API3_Exception
2143 */
00be9182 2144 public static function getFormParams($id, array $params) {
a13f3d8c 2145 if (!isset($params['is_pay_later'])) {
e02d7e96 2146 if (!empty($params['payment_processor_id'])) {
d25e4224
DG
2147 $params['is_pay_later'] = 0;
2148 }
62e432ac 2149 elseif (($params['amount'] ?? 0) !== 0) {
be2fb01f 2150 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
a13f3d8c 2151 'id' => $id,
21dfd5f5 2152 'return' => 'is_pay_later',
be2fb01f 2153 ]);
d25e4224 2154 }
be26f3e0 2155 }
a13f3d8c 2156 if (empty($params['price_set_id'])) {
be26f3e0
EM
2157 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
2158 }
2159 return $params;
2160 }
96025800 2161
75637f22
EM
2162 /**
2163 * Post form submission handling.
2164 *
2165 * This is also called from the test suite.
2166 *
2167 * @param int $contactID
2168 *
2169 * @return array
fb8d25da 2170 *
62c41ada 2171 * @throws \CRM_Core_Exception
fb8d25da 2172 * @throws \CiviCRM_API3_Exception
2173 * @throws \Civi\API\Exception\UnauthorizedException
75637f22
EM
2174 */
2175 protected function processFormSubmission($contactID) {
858f7096 2176 if (!isset($this->_params['payment_processor_id'])) {
2177 // If there is no processor we are using the pay-later manual pseudo-processor.
2178 // (note it might make sense to make this a row in the processor table in the db).
2179 $this->_params['payment_processor_id'] = 0;
2180 }
036c6315 2181 if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] === 0) {
75637f22
EM
2182 $this->_params['is_pay_later'] = $isPayLater = TRUE;
2183 }
58466af1 2184
2185 if (!empty($this->_ccid)) {
2186 $this->_params['contribution_id'] = $this->_ccid;
2187 }
67c998f4
JP
2188 //Set email-bltID if pre/post profile contains an email.
2189 if ($this->_emailExists == TRUE) {
2190 foreach ($this->_params as $key => $val) {
2191 if (substr($key, 0, 6) == 'email-' && empty($this->_params["email-{$this->_bltID}"])) {
2192 $this->_params["email-{$this->_bltID}"] = $this->_params[$key];
2193 }
2194 }
2195 }
75637f22 2196 // add a description field at the very beginning
6489e3de
SL
2197 $title = !empty($this->_values['frontend_title']) ? $this->_values['frontend_title'] : $this->_values['title'];
2198 $this->_params['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $title);
75637f22 2199
9c1bc317 2200 $this->_params['accountingCode'] = $this->_values['accountingCode'] ?? NULL;
75637f22
EM
2201
2202 // fix currency ID
2203 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
2204
a55e39e9 2205 CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($this->_params);
2206
dccd9f4f 2207 // CRM-18854
f3acfdd9 2208 if (!empty($this->_params['is_pledge']) && empty($this->_values['pledge_id']) && !empty($this->_values['adjust_recur_start_date'])) {
dccd9f4f 2209 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
b99f3e96
CW
2210 if (!empty($this->_params['start_date']) || empty($pledgeBlock['is_pledge_start_date_visible'])
2211 || empty($pledgeBlock['is_pledge_start_date_editable'])) {
9c1bc317 2212 $pledgeStartDate = $this->_params['start_date'] ?? NULL;
dccd9f4f
ERL
2213 $this->_params['receive_date'] = CRM_Pledge_BAO_Pledge::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2214 $recurParams = CRM_Pledge_BAO_Pledge::buildRecurParams($this->_params);
2215 $this->_params = array_merge($this->_params, $recurParams);
2216 }
2217 }
2218
75637f22 2219 //carry payment processor id.
f3acfdd9 2220 if (!empty($this->_paymentProcessor['id'])) {
75637f22
EM
2221 $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
2222 }
f85b8063
KJ
2223
2224 $premiumParams = $membershipParams = $params = $this->_params;
75637f22
EM
2225 if (!empty($params['image_URL'])) {
2226 CRM_Contact_BAO_Contact::processImageParams($params);
2227 }
f85b8063 2228
be2fb01f 2229 $fields = ['email-Primary' => 1];
75637f22
EM
2230
2231 // get the add to groups
be2fb01f 2232 $addToGroups = [];
75637f22
EM
2233
2234 // now set the values for the billing location.
2235 foreach ($this->_fields as $name => $value) {
2236 $fields[$name] = 1;
2237
2238 // get the add to groups for uf fields
2239 if (!empty($value['add_to_group_id'])) {
2240 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2241 }
2242 }
2243
bddc8a28 2244 $fields = $this->formatParamsForPaymentProcessor($fields);
75637f22
EM
2245
2246 // billing email address
2247 $fields["email-{$this->_bltID}"] = 1;
2248
75637f22
EM
2249 // if onbehalf-of-organization contribution, take out
2250 // organization params in a separate variable, to make sure
2251 // normal behavior is continued. And use that variable to
2252 // process on-behalf-of functionality.
2f44fc96 2253 if (!empty($this->_values['onbehalf_profile_id']) && empty($this->_ccid)) {
be2fb01f
CW
2254 $behalfOrganization = [];
2255 $orgFields = ['organization_name', 'organization_id', 'org_option'];
75637f22
EM
2256 foreach ($orgFields as $fld) {
2257 if (array_key_exists($fld, $params)) {
2258 $behalfOrganization[$fld] = $params[$fld];
2259 unset($params[$fld]);
2260 }
2261 }
2262
2263 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2264 foreach ($params['onbehalf'] as $fld => $values) {
2265 if (strstr($fld, 'custom_')) {
2266 $behalfOrganization[$fld] = $values;
2267 }
2268 elseif (!(strstr($fld, '-'))) {
be2fb01f 2269 if (in_array($fld, [
75637f22
EM
2270 'contribution_campaign_id',
2271 'member_campaign_id',
be2fb01f 2272 ])) {
75637f22
EM
2273 $fld = 'campaign_id';
2274 }
2275 else {
2276 $behalfOrganization[$fld] = $values;
2277 }
2278 $this->_params[$fld] = $values;
2279 }
2280 }
2281 }
2282
2283 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2284 foreach ($params['onbehalf_location'] as $block => $vals) {
2285 //fix for custom data (of type checkbox, multi-select)
2286 if (substr($block, 0, 7) == 'custom_') {
2287 continue;
2288 }
2289 // fix the index of block elements
2290 if (is_array($vals)) {
2291 foreach ($vals as $key => $val) {
2292 //dont adjust the index of address block as
2293 //it's index is WRT to location type
2294 $newKey = ($block == 'address') ? $key : ++$key;
2295 $behalfOrganization[$block][$newKey] = $val;
2296 }
2297 }
2298 }
2299 unset($params['onbehalf_location']);
2300 }
2301 if (!empty($params['onbehalf[image_URL]'])) {
2302 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2303 }
2304 }
2305
2306 // check for profile double opt-in and get groups to be subscribed
2307 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
2308
2309 // since we are directly adding contact to group lets unset it from mailing
2310 if (!empty($addToGroups)) {
2311 foreach ($addToGroups as $groupId) {
2312 if (isset($subscribeGroupIds[$groupId])) {
2313 unset($subscribeGroupIds[$groupId]);
2314 }
2315 }
2316 }
2317
2318 foreach ($addToGroups as $k) {
2319 if (array_key_exists($k, $subscribeGroupIds)) {
2320 unset($addToGroups[$k]);
2321 }
2322 }
2323
2324 if (empty($contactID)) {
2325 $dupeParams = $params;
2326 if (!empty($dupeParams['onbehalf'])) {
2327 unset($dupeParams['onbehalf']);
2328 }
2329 if (!empty($dupeParams['honor'])) {
2330 unset($dupeParams['honor']);
2331 }
2332
be2fb01f 2333 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
75637f22
EM
2334
2335 // Fetch default greeting id's if creating a contact
2336 if (!$contactID) {
2337 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
2338 if (!isset($params[$greeting])) {
2339 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
2340 }
2341 }
2342 }
2343 $contactType = NULL;
2344 }
2345 else {
2346 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2347 }
297fac31
AE
2348
2349 // sudoman hack: re-insert filtered group memberships
2350 $params = CRM_Contact_Form_Edit_TagsAndGroups::reInsertFilteredGroupMemberships($this->_id, 'contribution', $contactID, TRUE, $params);
2351
75637f22
EM
2352 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
2353 $params,
2354 $fields,
2355 $contactID,
2356 $addToGroups,
2357 NULL,
2358 $contactType,
2359 TRUE
2360 );
2361
2362 // Make the contact ID associated with the contribution available at the Class level.
2363 // Also make available to the session.
2364 //@todo consider handling this in $this->getContactID();
2365 $this->set('contactID', $contactID);
2366 $this->_contactID = $contactID;
2367
2368 //get email primary first if exist
cbbbf0ef 2369 $subscriptionEmail = ['email' => $params['email-Primary'] ?? NULL];
75637f22 2370 if (!$subscriptionEmail['email']) {
9c1bc317 2371 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ?? NULL;
75637f22
EM
2372 }
2373 // subscribing contact to groups
2374 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2375 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2376 }
2377
2378 // If onbehalf-of-organization contribution / signup, add organization
2379 // and it's location.
a9653117 2380 if (isset($this->_values['onbehalf_profile_id']) &&
2381 isset($behalfOrganization['organization_name']) &&
2382 ($this->_values['is_for_organization'] == 2 ||
2383 !empty($this->_params['is_for_organization'])
2384 )
2385 ) {
be2fb01f 2386 $ufFields = [];
75637f22
EM
2387 foreach ($this->_fields['onbehalf'] as $name => $value) {
2388 $ufFields[$name] = 1;
2389 }
2390 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
2391 $this->_params, $ufFields
2392 );
2393 }
2394 elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
2395 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2396 // store current user id as related contact for later use for mailing / activity..
2397 $this->_values['related_contact'] = $contactID;
2398 $this->_params['related_contact'] = $contactID;
2399 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2400 $contactID = $this->_membershipContactID;
2401 }
2402
2403 // lets store the contactID in the session
2404 // for things like tell a friend
2405 $session = CRM_Core_Session::singleton();
2406 if (!$session->get('userID')) {
2407 $session->set('transaction.userID', $contactID);
2408 }
2409 else {
2410 $session->set('transaction.userID', NULL);
2411 }
2412
2413 $this->_useForMember = $this->get('useForMember');
2414
2415 // store the fact that this is a membership and membership type is selected
c6f840fa 2416 if ($this->isMembershipSelected($membershipParams)) {
75637f22
EM
2417 if (!$this->_useForMember) {
2418 $this->assign('membership_assign', TRUE);
2419 $this->set('membershipTypeID', $this->_params['selectMembership']);
2420 }
2421
2422 if ($this->_action & CRM_Core_Action::PREVIEW) {
2423 $membershipParams['is_test'] = 1;
2424 }
2425 if ($this->_params['is_pay_later']) {
2426 $membershipParams['is_pay_later'] = 1;
2427 }
75637f22 2428
2dc204ea 2429 if (isset($this->_params['onbehalf_contact_id'])) {
2430 $membershipParams['onbehalf_contact_id'] = $this->_params['onbehalf_contact_id'];
2431 }
75637f22
EM
2432 //inherit campaign from contribution page.
2433 if (!array_key_exists('campaign_id', $membershipParams)) {
9c1bc317 2434 $membershipParams['campaign_id'] = $this->_values['campaign_id'] ?? NULL;
75637f22
EM
2435 }
2436
3be4a20e 2437 $this->_params = CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
f2bca231 2438 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem);
75637f22
EM
2439 }
2440 else {
2441 // at this point we've created a contact and stored its address etc
2442 // all the payment processors expect the name and address to be in the
2443 // so we copy stuff over to first_name etc.
2444 $paymentParams = $this->_params;
f2bca231 2445 // Make it explict that we are letting the processConfirm function figure out the line items.
2446 $paymentParams['skipLineItem'] = 0;
75637f22 2447
1659de20
PN
2448 if (!isset($paymentParams['line_item'])) {
2449 $paymentParams['line_item'] = $this->_lineItem;
2450 }
2451
75637f22
EM
2452 if (!empty($paymentParams['onbehalf']) &&
2453 is_array($paymentParams['onbehalf'])
2454 ) {
2455 foreach ($paymentParams['onbehalf'] as $key => $value) {
2456 if (strstr($key, 'custom_')) {
2457 $this->_params[$key] = $value;
2458 }
2459 }
75637f22 2460 }
10490499 2461
1a3545fa 2462 $result = $this->processConfirm($paymentParams,
5fb28746 2463 $contactID,
46763692 2464 $this->wrangleFinancialTypeID($this->_values['financial_type_id']),
449f4c90 2465 ($this->_mode == 'test') ? 1 : 0,
cbbbf0ef 2466 $paymentParams['is_recur'] ?? NULL
75637f22 2467 );
82583880 2468
0193ebdb 2469 if (empty($result['is_payment_failure'])) {
2470 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2471 $this->postProcessPremium($premiumParams, $result['contribution']);
2472 }
2473 if (!empty($result['contribution'])) {
04b24bb5 2474 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
0193ebdb 2475 $this->completeTransaction($result, $result['contribution']->id);
a8a4259e
EM
2476 }
2477 return $result;
75637f22
EM
2478 }
2479 }
2480
c6f840fa
MWMC
2481 /**
2482 * Return True/False if we have a membership selected on the contribution page
2483 * @param array $membershipParams
2484 *
2485 * @return bool
2486 */
2487 private function isMembershipSelected($membershipParams) {
2488 $priceFieldIds = $this->get('memberPriceFieldIDS');
2489 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2490 && empty($priceFieldIds)) {
2491 return TRUE;
2492 }
2493 else {
2494 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2495 }
2496 return !empty($membershipParams['selectMembership']);
2497 }
2498
2499 /**
2500 * Extract the selected memberships from a priceSet
2501 *
2502 * @param array $membershipParams
2503 *
2504 * @return array
2505 */
2506 private function getMembershipParamsFromPriceSet($membershipParams) {
2507 $priceFieldIds = $this->get('memberPriceFieldIDS');
2508 if (empty($priceFieldIds)) {
2509 return $membershipParams;
2510 }
2511 $membershipParams['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2512 unset($priceFieldIds['id']);
2513 $membershipTypeIds = [];
2514 $membershipTypeTerms = [];
2515 foreach ($priceFieldIds as $priceFieldId) {
2516 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2517 if ($membershipTypeId) {
2518 $membershipTypeIds[] = $membershipTypeId;
2519 $term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?: 1;
2520 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ? $term : 1;
2521 }
2522 }
2523 $membershipParams['selectMembership'] = $membershipTypeIds;
2524 $membershipParams['types_terms'] = $membershipTypeTerms;
2525 return $membershipParams;
2526 }
2527
7dd9ca37
EM
2528 /**
2529 * Membership processing section.
2530 *
2531 * This is in a separate function as part of a move towards refactoring.
2532 *
2533 * @param int $contactID
2534 * @param array $membershipParams
2535 * @param array $premiumParams
f2bca231 2536 * @param array $formLineItems
7dd9ca37 2537 */
f2bca231 2538 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
0d9ff2d4 2539 // This could be set by a hook.
2540 if (!empty($this->_params['installments'])) {
2541 $membershipParams['installments'] = $this->_params['installments'];
2542 }
7dd9ca37
EM
2543 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2544 if (isset($this->_params['related_contact'])) {
2545 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
2546 }
2547 else {
2548 $membershipParams['cms_contactID'] = $contactID;
2549 }
2550
2551 if (!empty($membershipParams['onbehalf']) &&
2552 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2553 ) {
2554 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2555 }
2556
be2fb01f 2557 $customFieldsFormatted = $fieldTypes = [];
7dd9ca37
EM
2558 if (!empty($membershipParams['onbehalf']) &&
2559 is_array($membershipParams['onbehalf'])
2560 ) {
2561 foreach ($membershipParams['onbehalf'] as $key => $value) {
2562 if (strstr($key, 'custom_')) {
2563 $customFieldId = explode('_', $key);
2564 CRM_Core_BAO_CustomField::formatCustomField(
2565 $customFieldId[1],
2566 $customFieldsFormatted,
2567 $value,
2568 'Membership',
2569 NULL,
2570 $contactID
2571 );
2572 }
2573 }
be2fb01f 2574 $fieldTypes = ['Contact', 'Organization', 'Membership'];
7dd9ca37
EM
2575 }
2576
c6f840fa 2577 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
7dd9ca37
EM
2578 if (!empty($membershipParams['selectMembership'])) {
2579 // CRM-12233
f2bca231 2580 $membershipLineItems = $formLineItems;
7dd9ca37 2581 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
be2fb01f 2582 $membershipLineItems = [];
7dd9ca37
EM
2583 foreach ($this->_values['fee'] as $key => $feeValues) {
2584 if ($feeValues['name'] == 'membership_amount') {
2585 $fieldId = $this->_params['price_' . $key];
2586 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
2587 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
2588 break;
2589 }
2590 }
2591 }
4b6c8c1e 2592 try {
f2bca231 2593 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
4b6c8c1e 2594 }
d23860d8
SP
2595 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
2596 CRM_Core_Session::singleton()->setStatus($e->getMessage());
2597 if (!empty($this->_contributionID)) {
2598 CRM_Contribute_BAO_Contribution::failPayment($this->_contributionID,
2599 $contactID, $e->getMessage());
2600 }
2601 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2602 }
4b6c8c1e 2603 catch (CRM_Core_Exception $e) {
2604 CRM_Core_Session::singleton()->setStatus($e->getMessage());
2605 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2606 }
7dd9ca37
EM
2607 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
2608 // we need to explicitly create a CMS user in case of free memberships
2609 // since it is done under processConfirm for paid memberships
2610 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
2611 $membershipParams['cms_contactID'],
2612 'email-' . $this->_bltID
2613 );
2614 }
2615 }
2616 }
2617
0193ebdb 2618 /**
2619 * Complete transaction if payment has been processed.
2620 *
2621 * Check the result for a success outcome & if paid then complete the transaction.
2622 *
2623 * Completing will trigger update of related entities and emails.
2624 *
2625 * @param array $result
2626 * @param int $contributionID
2627 *
ec7e3954
E
2628 * @throws \CiviCRM_API3_Exception
2629 * @throws \Exception
0193ebdb 2630 */
2631 protected function completeTransaction($result, $contributionID) {
cbbbf0ef 2632 if (($result['payment_status_id'] ?? NULL) == 1) {
0193ebdb 2633 try {
be2fb01f 2634 civicrm_api3('contribution', 'completetransaction', [
a55e39e9 2635 'id' => $contributionID,
6b409353 2636 'trxn_id' => $result['trxn_id'] ?? NULL,
cbbbf0ef 2637 'payment_processor_id' => $result['payment_processor_id'] ?? $this->_paymentProcessor['id'],
a55e39e9 2638 'is_transactional' => FALSE,
6b409353
CW
2639 'fee_amount' => $result['fee_amount'] ?? NULL,
2640 'receive_date' => $result['receive_date'] ?? NULL,
2641 'card_type_id' => $result['card_type_id'] ?? NULL,
2642 'pan_truncation' => $result['pan_truncation'] ?? NULL,
be2fb01f 2643 ]);
0193ebdb 2644 }
2645 catch (CiviCRM_API3_Exception $e) {
2646 if ($e->getErrorCode() != 'contribution_completed') {
2647 throw new CRM_Core_Exception('Failed to update contribution in database');
2648 }
2649 }
2650 }
2651 }
2652
77beddbe 2653 /**
2654 * Bounce the user back to retry when an error occurs.
2655 *
2656 * @param string $message
2657 */
2658 protected function bounceOnError($message) {
2659 CRM_Core_Session::singleton()
2660 ->setStatus(ts("Payment Processor Error message :") .
2661 $message);
2662 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
2663 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
2664 ));
2665 }
2666
74c1b622 2667 /**
2668 * Is a payment being made.
2669 *
2670 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
2671 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
2672 * @param CRM_Core_Form $form
2673 *
2674 * @return bool
2675 */
2676 protected static function isPaymentTransaction($form) {
2677 return $form->_amount >= 0.0;
2678 }
2679
2680 /**
2681 * Process payment after confirmation.
2682 *
74c1b622 2683 * @param array $paymentParams
2684 * Array with payment related key.
2685 * value pairs
2686 * @param int $contactID
2687 * Contact id.
2688 * @param int $financialTypeID
2689 * Financial type id.
2690 * @param bool $isTest
2691 * @param bool $isRecur
2692 *
2693 * @throws CRM_Core_Exception
2694 * @throws Exception
2695 * @return array
2696 * associated array
74c1b622 2697 */
1a3545fa 2698 public function processConfirm(
74c1b622 2699 &$paymentParams,
2700 $contactID,
2701 $financialTypeID,
2702 $isTest,
2703 $isRecur
fb8d25da 2704 ): array {
1a3545fa 2705 $form = $this;
74c1b622 2706 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
2707 $isPaymentTransaction = self::isPaymentTransaction($form);
2708
2709 $financialType = new CRM_Financial_DAO_FinancialType();
2710 $financialType->id = $financialTypeID;
2711 $financialType->find(TRUE);
2712 if ($financialType->is_deductible) {
2713 $form->assign('is_deductible', TRUE);
2714 $form->set('is_deductible', TRUE);
2715 }
2716
2717 // add some financial type details to the params list
2718 // if folks need to use it
c2978fe0 2719 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $financialType->id;
74c1b622 2720 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
2721 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
2722 //CRM-11456
2723 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($financialTypeID);
2724 $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
2725 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
2726
2727 //fix for CRM-16317
2728 if (empty($form->_params['receive_date'])) {
2729 $form->_params['receive_date'] = date('YmdHis');
2730 }
2731 if (!empty($form->_params['start_date'])) {
2732 $form->_params['start_date'] = date('YmdHis');
2733 }
2734 $form->assign('receive_date',
2735 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
2736 );
2737
2738 if (empty($form->_values['amount'])) {
2739 // If the amount is not in _values[], set it
2740 $form->_values['amount'] = $form->_params['amount'];
2741 }
2742
2743 if (isset($paymentParams['contribution_source'])) {
2744 $paymentParams['source'] = $paymentParams['contribution_source'];
2745 }
2746 if ($isPaymentTransaction) {
2747 $contributionParams = [
2748 'id' => $paymentParams['contribution_id'] ?? NULL,
2749 'contact_id' => $contactID,
2750 'is_test' => $isTest,
2751 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
2752 ];
2753
2754 // CRM-21200: Don't overwrite contribution details during 'Pay now' payment
2755 if (empty($form->_params['contribution_id'])) {
2756 $contributionParams['contribution_page_id'] = $form->_id;
2757 $contributionParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values));
2758 }
2759 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
2760 else {
2761 // contribution.source only allows 255 characters so we are using ellipsify(...) to ensure it.
2762 $contributionParams['source'] = CRM_Utils_String::ellipsify(
2763 ts('Paid later via page ID: %1. %2', [
2764 1 => $form->_id,
2765 2 => $contributionParams['source'],
2766 ]),
2767 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
2768 220
2769 );
2770 }
2771
2772 if (isset($paymentParams['line_item'])) {
2773 // @todo make sure this is consisently set at this point.
2774 $contributionParams['line_item'] = $paymentParams['line_item'];
2775 }
2776 if (!empty($form->_paymentProcessor)) {
2777 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
2778 }
2779
2780 // @todo this is the wrong place for this - it should be done as close to form submission
2781 // as possible
2782 $paymentParams['amount'] = CRM_Utils_Rule::cleanMoney($paymentParams['amount']);
2783 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
2784 $form,
2785 $paymentParams,
2786 NULL,
2787 $contributionParams,
2788 $financialType,
2789 TRUE,
2790 $form->_bltID,
2791 $isRecur
2792 );
2ebe2e8c 2793 // CRM-13074 - create the CMSUser after the transaction is completed as it
2794 // is not appropriate to delete a valid contribution if a user create problem occurs
99ee765c 2795 if (isset($this->_params['related_contact'])) {
2796 $contactID = $this->_params['related_contact'];
2ebe2e8c 2797 }
99ee765c 2798 elseif (isset($this->_params['cms_contactID'])) {
2799 $contactID = $this->_params['cms_contactID'];
2ebe2e8c 2800 }
99ee765c 2801 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($this->_params,
2ebe2e8c 2802 $contactID,
2803 'email-' . $form->_bltID
2804 );
74c1b622 2805
2806 $paymentParams['item_name'] = $form->_params['description'];
2807
2808 $paymentParams['qfKey'] = empty($paymentParams['qfKey']) ? $form->controller->_key : $paymentParams['qfKey'];
2809 if ($paymentParams['skipLineItem']) {
2810 // We are not processing the line item here because we are processing a membership.
2811 // Do not continue with contribution processing in this function.
2812 return ['contribution' => $contribution];
2813 }
2814
2815 $paymentParams['contributionID'] = $contribution->id;
2816 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
2817
2818 if (!empty($form->_params['is_recur']) && $contribution->contribution_recur_id) {
2819 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
2820 }
2821 if (isset($paymentParams['contribution_source'])) {
2822 $form->_params['source'] = $paymentParams['contribution_source'];
2823 }
2824
2825 // get the price set values for receipt.
2826 if ($form->_priceSetId && $form->_lineItem) {
2827 $form->_values['lineItem'] = $form->_lineItem;
2828 $form->_values['priceSetID'] = $form->_priceSetId;
2829 }
2830
2831 $form->_values['contribution_id'] = $contribution->id;
2832 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
2833
2834 if (!empty($form->_paymentProcessor)) {
2835 try {
2836 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
2837 if ($form->_contributeMode == 'notify') {
2838 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
2839 // and always calling it first.
2840 $form->postProcessHook();
2841 }
2842 $result = $payment->doPayment($paymentParams);
2843 $form->_params = array_merge($form->_params, $result);
2844 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
2845 if (!empty($result['trxn_id'])) {
2846 $contribution->trxn_id = $result['trxn_id'];
2847 }
2848 if (!empty($result['payment_status_id'])) {
2849 $contribution->payment_status_id = $result['payment_status_id'];
2850 }
2851 $result['contribution'] = $contribution;
2852 if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')
2853 && $payment->isSendReceiptForPending()) {
2854 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
2855 $form->_values,
2856 $contribution->is_test
2857 );
2858 }
2859 return $result;
2860 }
2861 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
2862 // Clean up DB as appropriate.
2863 if (!empty($paymentParams['contributionID'])) {
2864 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
2865 $paymentParams['contactID'], $e->getMessage());
2866 }
2867 if (!empty($paymentParams['contributionRecurID'])) {
2868 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
2869 }
2870
2871 $result['is_payment_failure'] = TRUE;
2872 $result['error'] = $e;
2873 return $result;
2874 }
2875 }
2876 }
2877
2878 // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
2879 // manual processor, so it's unclear what this set is for and whether the following send ever fires.
2880 $form->set('params', $form->_params);
2881
2882 if ($form->_params['amount'] == 0) {
2883 // This is kind of a back-up for pay-later $0 transactions.
2884 // In other flows they pick up the manual processor & get dealt with above (I
2885 // think that might be better...).
2886 return [
2887 'payment_status_id' => 1,
2888 'contribution' => $contribution,
2889 'payment_processor_id' => 0,
2890 ];
2891 }
2892
2893 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
2894 $form->_values,
2895 $contribution->is_test
2896 );
2897 }
2898
6a488035 2899}