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