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