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