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