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