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