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