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