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