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