Merge pull request #10021 from jitendrapurohit/CRM-20246
[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;
946 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
5afce5ad 947 $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online, $form);
51e89def 948
75637f22
EM
949 $now = date('YmdHis');
950 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
951 if ($isEmailReceipt) {
952 $receiptDate = $now;
6a488035
TO
953 }
954
75637f22 955 if (isset($params['amount'])) {
f6261e9d 956 $contributionParams = array_merge(self::getContributionParams(
f7248cb7 957 $params, $financialType->id, $nonDeductibleAmount, TRUE,
f6261e9d 958 $result, $receiptDate,
959 $recurringContributionID), $contributionParams
75637f22 960 );
f6261e9d 961 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
6a488035 962
aaffa79f 963 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
75637f22
EM
964 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
965 if ($invoicing) {
966 $dataArray = array();
f6261e9d 967 // @todo - interrogate the line items passed in on the params array.
968 // No reason to assume line items will be set on the form.
75637f22
EM
969 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
970 foreach ($lineItemValue as $key => $value) {
971 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
972 if (isset($dataArray[$value['tax_rate']])) {
973 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
974 }
975 else {
976 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
977 }
978 }
6a488035
TO
979 }
980 }
75637f22
EM
981 $smarty = CRM_Core_Smarty::singleton();
982 $smarty->assign('dataArray', $dataArray);
983 $smarty->assign('totalTaxAmount', $params['tax_amount']);
984 }
985 if (is_a($contribution, 'CRM_Core_Error')) {
986 $message = CRM_Core_Error::getMessages($contribution);
987 CRM_Core_Error::fatal($message);
6a488035
TO
988 }
989
75637f22
EM
990 // lets store it in the form variable so postProcess hook can get to this and use it
991 $form->_contributionID = $contribution->id;
992 }
6a488035 993
7a13735b 994 // process soft credit / pcp params first
995 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
75637f22 996
7a13735b 997 //CRM-13981, processing honor contact into soft-credit contribution
998 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
75637f22 999
75637f22 1000 if ($isPledge) {
356bfcaf 1001 $form = self::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
6a488035 1002 }
6a488035 1003
75637f22 1004 if ($online && $contribution) {
09108d7d 1005 CRM_Core_BAO_CustomValueTable::postProcess($params,
75637f22
EM
1006 'civicrm_contribution',
1007 $contribution->id,
1008 'Contribution'
1009 );
1010 }
1011 elseif ($contribution) {
1012 //handle custom data.
1013 $params['contribution_id'] = $contribution->id;
1014 if (!empty($params['custom']) &&
1015 is_array($params['custom']) &&
1016 !is_a($contribution, 'CRM_Core_Error')
6a488035 1017 ) {
75637f22 1018 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
6a488035 1019 }
75637f22
EM
1020 }
1021 // Save note
1022 if ($contribution && !empty($params['contribution_note'])) {
1023 $noteParams = array(
1024 'entity_table' => 'civicrm_contribution',
1025 'note' => $params['contribution_note'],
1026 'entity_id' => $contribution->id,
1027 'contact_id' => $contribution->contact_id,
1028 'modified_date' => date('Ymd'),
cc789d46 1029 );
75637f22
EM
1030
1031 CRM_Core_BAO_Note::add($noteParams, array());
cc789d46 1032 }
cc789d46 1033
75637f22
EM
1034 if (isset($params['related_contact'])) {
1035 $contactID = $params['related_contact'];
cc789d46 1036 }
75637f22
EM
1037 elseif (isset($params['cms_contactID'])) {
1038 $contactID = $params['cms_contactID'];
6a488035 1039 }
75637f22
EM
1040
1041 //create contribution activity w/ individual and target
1042 //activity w/ organisation contact id when onbelf, CRM-4027
1043 $targetContactID = NULL;
1044 if (!empty($params['hidden_onbehalf_profile'])) {
1045 $targetContactID = $contribution->contact_id;
1046 $contribution->contact_id = $contactID;
1047 }
1048
1049 // create an activity record
1050 if ($contribution) {
1051 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1052 }
1053
1054 $transaction->commit();
1055 // CRM-13074 - create the CMSUser after the transaction is completed as it
1056 // is not appropriate to delete a valid contribution if a user create problem occurs
1057 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1058 $contactID,
1059 'email-' . $billingLocationID
1060 );
1061 return $contribution;
6a488035
TO
1062 }
1063
1064 /**
75637f22 1065 * Create the recurring contribution record.
6a488035 1066 *
75637f22
EM
1067 * @param CRM_Core_Form $form
1068 * @param array $params
1069 * @param int $contactID
1070 * @param string $contributionType
75637f22 1071 *
449f4c90 1072 * @return int|null
6a488035 1073 */
449f4c90 1074 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
cde484fd 1075
449f4c90 1076 if (empty($params['is_recur'])) {
75637f22
EM
1077 return NULL;
1078 }
6a488035 1079
75637f22
EM
1080 $recurParams = array('contact_id' => $contactID);
1081 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1082 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1083 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1084 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1085 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1086 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1087 $recurParams['currency'] = CRM_Utils_Array::value('currency', $params);
f69a9ac3 1088 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
6a488035 1089
75637f22
EM
1090 // CRM-14354: For an auto-renewing membership with an additional contribution,
1091 // if separate payments is not enabled, make sure only the membership fee recurs
1092 if (!empty($form->_membershipBlock)
1093 && $form->_membershipBlock['is_separate_payment'] === '0'
1094 && isset($params['selectMembership'])
1095 && $form->_values['is_allow_other_amount'] == '1'
1096 // CRM-16331
1097 && !empty($form->_membershipTypeValues)
1098 && !empty($form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'])
1099 ) {
1100 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1101 }
6a488035 1102
75637f22
EM
1103 $recurParams['is_test'] = 0;
1104 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1105 (isset($form->_mode) && ($form->_mode == 'test'))
1106 ) {
1107 $recurParams['is_test'] = 1;
1108 }
6a488035 1109
75637f22
EM
1110 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1111 if (!empty($params['receive_date'])) {
12e53254 1112 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
75637f22
EM
1113 }
1114 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1115 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1116 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1117 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1118 // we need to add a unique trxn_id to avoid a unique key error
1119 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1120 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1121 $recurParams['financial_type_id'] = $contributionType->id;
6a488035 1122
449f4c90 1123 $campaignId = CRM_Utils_Array::value('campaign_id', $params, CRM_Utils_Array::value('campaign_id', $form->_values));
75637f22 1124 $recurParams['campaign_id'] = $campaignId;
75637f22
EM
1125 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1126 if (is_a($recurring, 'CRM_Core_Error')) {
1127 CRM_Core_Error::displaySessionError($recurring);
1128 $urlString = 'civicrm/contribute/transact';
1129 $urlParams = '_qf_Main_display=true';
1130 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1131 $urlString = 'civicrm/contact/view/contribution';
1132 $urlParams = "action=add&cid={$form->_contactID}";
1133 if ($form->_mode) {
1134 $urlParams .= "&mode={$form->_mode}";
1135 }
6a488035 1136 }
75637f22 1137 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
6a488035 1138 }
dccd9f4f
ERL
1139 // Only set contribution recur ID for contributions since offline membership recur payments are handled somewhere else.
1140 if (!is_a($form, "CRM_Member_Form_Membership")) {
1141 $form->_params['contributionRecurID'] = $recurring->id;
1142 }
75637f22
EM
1143
1144 return $recurring->id;
6a488035
TO
1145 }
1146
1147 /**
75637f22 1148 * Add on behalf of organization and it's location.
cd6994fc 1149 *
75637f22
EM
1150 * This situation occurs when on behalf of is enabled for the contribution page and the person
1151 * signing up does so on behalf of an organization.
a1a94e61 1152 *
75637f22
EM
1153 * @param array $behalfOrganization
1154 * array of organization info.
1155 * @param int $contactID
1156 * individual contact id. One.
1157 * who is doing the process of signup / contribution.
9fc4e1d9 1158 *
75637f22
EM
1159 * @param array $values
1160 * form values array.
1161 * @param array $params
1162 * @param array $fields
1163 * Array of fields from the onbehalf profile relevant to the organization.
6a488035 1164 */
75637f22 1165 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
33260076 1166 $isNotCurrentEmployer = FALSE;
75637f22
EM
1167 $dupeIDs = array();
1168 $orgID = NULL;
6cc679d2 1169 if (!empty($behalfOrganization['organization_id'])) {
75637f22
EM
1170 $orgID = $behalfOrganization['organization_id'];
1171 unset($behalfOrganization['organization_id']);
33260076 1172 }
1173 // create employer relationship with $contactID only when new organization is there
1174 // else retain the existing relationship
1175 else {
1176 // get the Employee relationship type id
1177 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
b9dc56f5 1178
33260076 1179 // keep relationship params ready
1180 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1181 $relParams['is_permission_a_b'] = 1;
1182 $relParams['is_active'] = 1;
1183 $isNotCurrentEmployer = TRUE;
bb06e9ed 1184 }
6a488035 1185
75637f22
EM
1186 // formalities for creating / editing organization.
1187 $behalfOrganization['contact_type'] = 'Organization';
c8bde7ea 1188
75637f22
EM
1189 if (!$orgID) {
1190 // check if matching organization contact exists
03b40a7b 1191 $dupeID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($behalfOrganization, 'Organization', 'Unsupervised', array(), FALSE);
6a488035 1192
75637f22
EM
1193 // CRM-6243 says to pick the first org even if more than one match
1194 if (count($dupeIDs) >= 1) {
03b40a7b 1195 $behalfOrganization['contact_id'] = $orgID = $dupeID;
75637f22
EM
1196 // don't allow name edit
1197 unset($behalfOrganization['organization_name']);
6a488035
TO
1198 }
1199 }
1200 else {
75637f22
EM
1201 // if found permissioned related organization, allow location edit
1202 $behalfOrganization['contact_id'] = $orgID;
1203 // don't allow name edit
1204 unset($behalfOrganization['organization_name']);
6a488035
TO
1205 }
1206
75637f22
EM
1207 // handling for image url
1208 if (!empty($behalfOrganization['image_URL'])) {
1209 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
6a488035
TO
1210 }
1211
75637f22
EM
1212 // create organization, add location
1213 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1214 NULL, NULL, 'Organization'
1215 );
1216 // create relationship
33260076 1217 if ($isNotCurrentEmployer) {
1218 $relParams['contact_check'][$orgID] = 1;
1219 $cid = array('contact' => $contactID);
1220 CRM_Contact_BAO_Relationship::legacyCreateMultiple($relParams, $cid);
1221 }
1f1740fe 1222
75637f22
EM
1223 // if multiple match - send a duplicate alert
1224 if ($dupeIDs && (count($dupeIDs) > 1)) {
1225 $values['onbehalf_dupe_alert'] = 1;
1226 // required for IPN
1227 $params['onbehalf_dupe_alert'] = 1;
6a488035 1228 }
cde484fd 1229
75637f22
EM
1230 // make sure organization-contact-id is considered for recording
1231 // contribution/membership etc..
1232 if ($contactID != $orgID) {
1233 // take a note of contact-id, so we can send the
1234 // receipt to individual contact as well.
6a488035 1235
75637f22
EM
1236 // required for mailing/template display ..etc
1237 $values['related_contact'] = $contactID;
6a488035 1238
0462a5b2 1239 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1240 $params['onbehalf_contact_id'] = $contactID;
1241
75637f22
EM
1242 //make this employee of relationship as current
1243 //employer / employee relationship, CRM-3532
33260076 1244 if ($isNotCurrentEmployer &&
75637f22
EM
1245 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1246 ) {
33260076 1247 $isNotCurrentEmployer = FALSE;
6a488035 1248 }
6a488035 1249
33260076 1250 if (!$isNotCurrentEmployer && $orgID) {
75637f22
EM
1251 //build current employer params
1252 $currentEmpParams[$contactID] = $orgID;
1253 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
6a488035 1254 }
6a488035 1255
75637f22
EM
1256 // contribution / signup will be done using this
1257 // organization id.
1258 $contactID = $orgID;
6a488035 1259 }
75637f22
EM
1260 }
1261
6a488035 1262 /**
75637f22 1263 * Function used to send notification mail to pcp owner.
6a488035 1264 *
75637f22 1265 * This is used by contribution and also event PCPs.
03110609 1266 *
75637f22
EM
1267 * @param object $contribution
1268 * @param object $contributionSoft
1269 * Contribution object.
12f92dbd 1270 */
12f92dbd 1271 public static function pcpNotifyOwner($contribution, $contributionSoft) {
5fe87df6
N
1272 $params = array('id' => $contributionSoft->pcp_id);
1273 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1274 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1275
1276 if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') &&
1277 (($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') &&
1278 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify')) ||
1279 $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) {
1280 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
1281 "reset=1&id={$contributionSoft->pcp_id}",
1282 TRUE, NULL, FALSE, TRUE
1283 );
12f92dbd 1284 // set email in the template here
5fe87df6 1285
b576d770 1286 if (CRM_Core_BAO_LocationType::getBilling()) {
1287 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id,
1288 FALSE, CRM_Core_BAO_LocationType::getBilling());
5fe87df6
N
1289 }
1290 // get primary location email if no email exist( for billing location).
1291 if (!$email) {
1292 list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id);
1293 }
1294 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id);
12f92dbd 1295 $tplParams = array(
5fe87df6 1296 'page_title' => $pcpInfo['title'],
12f92dbd
N
1297 'receive_date' => $contribution->receive_date,
1298 'total_amount' => $contributionSoft->amount,
1299 'donors_display_name' => $donorName,
5fe87df6
N
1300 'donors_email' => $email,
1301 'pcpInfoURL' => $pcpInfoURL,
12f92dbd 1302 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll,
dd55005c 1303 'currency' => $contributionSoft->currency,
12f92dbd
N
1304 );
1305 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
1306 $sendTemplateParams = array(
1307 'groupName' => 'msg_tpl_workflow_contribution',
1308 'valueName' => 'pcp_owner_notify',
1309 'contactId' => $contributionSoft->contact_id,
5fe87df6
N
1310 'toEmail' => $ownerEmail,
1311 'toName' => $ownerName,
12f92dbd
N
1312 'from' => "$domainValues[0] <$domainValues[1]>",
1313 'tplParams' => $tplParams,
1314 'PDFFilename' => 'receipt.pdf',
1315 );
1316 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1317 }
1318 }
1319
1320 /**
5e4f7f74
EM
1321 * Function used to se pcp related defaults / params.
1322 *
1323 * This is used by contribution and also event PCPs
6a488035 1324 *
014c4014
TO
1325 * @param CRM_Core_Form $page
1326 * Form object.
1327 * @param array $params
6a488035 1328 *
cd6994fc 1329 * @return array
6a488035 1330 */
00be9182 1331 public static function processPcp(&$page, $params) {
547206bc 1332 $params['pcp_made_through_id'] = $page->_pcpId;
6a488035 1333 $page->assign('pcpBlock', TRUE);
8cc574cf 1334 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
6a488035
TO
1335 $params['pcp_roll_nickname'] = ts('Anonymous');
1336 $params['pcp_is_anonymous'] = 1;
1337 }
1338 else {
1339 $params['pcp_is_anonymous'] = 0;
1340 }
1341 foreach (array(
547206bc 1342 'pcp_display_in_roll',
1343 'pcp_is_anonymous',
1344 'pcp_roll_nickname',
21dfd5f5 1345 'pcp_personal_note',
547206bc 1346 ) as $val) {
a7488080 1347 if (!empty($params[$val])) {
6a488035
TO
1348 $page->assign($val, $params[$val]);
1349 }
1350 }
1351
1352 return $params;
1353 }
705b4205
EM
1354
1355 /**
5e4f7f74
EM
1356 * Process membership.
1357 *
5624f515 1358 * @param array $membershipParams
014c4014 1359 * @param int $contactID
5624f515
EM
1360 * @param array $customFieldsFormatted
1361 * @param array $fieldTypes
1362 * @param array $premiumParams
014c4014
TO
1363 * @param array $membershipLineItems
1364 * Line items specifically relating to memberships.
705b4205 1365 */
4b6c8c1e 1366 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
f2bca231 1367 $membershipLineItems) {
8bc79dfc 1368
4b6c8c1e 1369 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1370 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1371 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1372 $isPending = $this->getIsPending();
5624f515 1373
4b6c8c1e 1374 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1fc22ffa 1375 $this->_values['membership_name'] = CRM_Utils_Array::value('name', $membershipType);
7c113627 1376
4b6c8c1e 1377 $isPaidMembership = FALSE;
1378 if ($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1379 //amount must be greater than zero for
1380 //adding contribution record to contribution table.
1381 //this condition arises when separate membership payment is
1382 //enabled and contribution amount is not selected. fix for CRM-3010
1383 $isPaidMembership = TRUE;
1384 }
1385 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
7c113627 1386
4b6c8c1e 1387 if ($this->_values['amount_block_is_active']) {
1388 $financialTypeID = $this->_values['financial_type_id'];
705b4205 1389 }
4b6c8c1e 1390 else {
1391 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id', $membershipParams));
705b4205 1392 }
4b6c8c1e 1393
1394 if (CRM_Utils_Array::value('membership_source', $this->_params)) {
1395 $membershipParams['contribution_source'] = $this->_params['membership_source'];
1396 }
1397
1398 $this->postProcessMembership($membershipParams, $contactID,
1399 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $financialTypeID,
f2bca231 1400 $membershipLineItems, $isPending);
4b6c8c1e 1401
1402 $this->assign('membership_assign', TRUE);
1403 $this->set('membershipTypeID', $membershipParams['selectMembership']);
705b4205 1404 }
fb49fa48 1405
8bc79dfc 1406 /**
668ddfc2
EM
1407 * Process the Memberships.
1408 *
1409 * @param array $membershipParams
1410 * Array of membership fields.
1411 * @param int $contactID
1412 * Contact id.
1413 * @param CRM_Contribute_Form_Contribution_Confirm $form
1414 * Confirmation form object.
1415 *
1416 * @param array $premiumParams
1417 * @param null $customFieldsFormatted
1418 * @param null $includeFieldTypes
1419 *
1420 * @param array $membershipDetails
1421 *
1422 * @param array $membershipTypeIDs
1423 *
1424 * @param bool $isPaidMembership
1425 * @param array $membershipID
1426 *
1427 * @param bool $isProcessSeparateMembershipTransaction
1428 *
1429 * @param int $financialTypeID
f2bca231 1430 * @param array $unprocessedLineItems
1431 * Line items for payment options chosen on the form.
668ddfc2
EM
1432 * @param bool $isPending
1433 *
1434 * @throws \CRM_Core_Exception
1435 */
1436 protected function postProcessMembership(
1437 $membershipParams, $contactID, &$form, $premiumParams,
1438 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
f2bca231 1439 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems, $isPending) {
1440
82583880 1441 $membershipContribution = NULL;
668ddfc2 1442 $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
28da8ecd 1443 $errors = $paymentResults = array();
858f7096 1444 $form->_values['isMembership'] = TRUE;
449f4c90 1445 $isRecurForFirstTransaction = CRM_Utils_Array::value('is_recur', $form->_values, CRM_Utils_Array::value('is_recur', $membershipParams));
f2bca231 1446
858f7096 1447 $totalAmount = $membershipParams['amount'];
449f4c90 1448
668ddfc2
EM
1449 if ($isPaidMembership) {
1450 if ($isProcessSeparateMembershipTransaction) {
1451 // If we have 2 transactions only one can use the invoice id.
1452 $membershipParams['invoiceID'] .= '-2';
449f4c90 1453 if (!empty($membershipParams['auto_renew'])) {
1454 $isRecurForFirstTransaction = FALSE;
1455 }
668ddfc2
EM
1456 }
1457
417c6834 1458 if (!$isProcessSeparateMembershipTransaction) {
f2bca231 1459 // Skip line items in the contribution processing transaction.
1460 // We will create them with the membership for proper linking.
417c6834 1461 $membershipParams['skipLineItem'] = 1;
1462 }
8e8d287f 1463 else {
1464 $membershipParams['total_amount'] = $totalAmount;
f2bca231 1465 $membershipParams['skipLineItem'] = 0;
8e8d287f 1466 CRM_Price_BAO_LineItem::getLineItemArray($membershipParams);
1467
1468 }
f2bca231 1469 $paymentResult = CRM_Contribute_BAO_Contribution_Utils::processConfirm(
1470 $form,
1471 $membershipParams,
5fb28746 1472 $contactID,
668ddfc2 1473 $financialTypeID,
449f4c90 1474 $isTest,
1475 $isRecurForFirstTransaction
668ddfc2 1476 );
668ddfc2 1477
82583880 1478 if (!empty($paymentResult['contribution'])) {
5fb28746 1479 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
668ddfc2
EM
1480 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1481 $membershipContribution = $paymentResult['contribution'];
1482 // Save the contribution ID so that I can be used in email receipts
1483 // For example, if you need to generate a tax receipt for the donation only.
1484 $form->_values['contribution_other_id'] = $membershipContribution->id;
1485 }
1486 }
1487
1488 if ($isProcessSeparateMembershipTransaction) {
1489 try {
f2bca231 1490 $form->_lineItem = $unprocessedLineItems;
668ddfc2
EM
1491 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1492 unset($membershipParams['is_recur']);
1493 }
8e8d287f 1494 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, array('skipLineItem' => 1)),
f2bca231 1495 $isTest, $unprocessedLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
63137f3a 1496 $paymentResults[] = array('contribution_id' => $membershipContribution->id, 'result' => $secondPaymentResult);
668ddfc2
EM
1497 }
1498 catch (CRM_Core_Exception $e) {
1499 $errors[2] = $e->getMessage();
1500 $membershipContribution = NULL;
1501 }
1502 }
1503
1504 $membership = NULL;
1505 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1506 $membershipContributionID = $membershipContribution->id;
1507 }
1508
1509 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1510 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1511 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1512 }
1513 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1514 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1515 $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
65e172a3 1516
1517 $membershipLines = $nonMembershipLines = array();
1518 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1519 foreach ($lines as $line) {
1520 if (!empty($line['membership_type_id'])) {
1521 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1522 }
1523 }
1524 }
1525
1526 $i = 1;
668ddfc2 1527 foreach ($membershipTypeIDs as $memType) {
aa1d1808 1528 $membershipLineItems = array();
65e172a3 1529 if ($i < count($membershipTypeIDs)) {
1530 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1531 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1532 }
1533 else {
1534 $membershipLineItems = $unprocessedLineItems;
1535 }
1536 $i++;
668ddfc2
EM
1537 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
1538 if (!empty($membershipContribution)) {
1539 $pendingStatus = CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name');
1540 $pending = ($membershipContribution->contribution_status_id == $pendingStatus) ? TRUE : FALSE;
1541 }
1542 else {
1543 $pending = $isPending;
1544 }
1545 $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
1546
1547 $membershipSource = NULL;
1548 if (!empty($form->_params['membership_source'])) {
1549 $membershipSource = $form->_params['membership_source'];
1550 }
1551 elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
1552 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
1553 }
1554 $isPayLater = NULL;
1555 if (isset($form->_params)) {
1556 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
1557 }
1558 $campaignId = NULL;
1559 if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
1560 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
1561 if (!array_key_exists('campaign_id', $form->_params)) {
1562 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1563 }
1564 }
1565
356bfcaf 1566 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership::processMembership(
668ddfc2
EM
1567 $contactID, $memType, $isTest,
1568 date('YmdHis'), CRM_Utils_Array::value('cms_contactID', $membershipParams),
1569 $customFieldsFormatted,
1570 $numTerms, $membershipID, $pending,
13a16f43 1571 $contributionRecurID, $membershipSource, $isPayLater, $campaignId, array(), $membershipContribution,
65e172a3 1572 $membershipLineItems
668ddfc2 1573 );
bd53b1b9 1574
668ddfc2
EM
1575 $form->set('renewal_mode', $renewalMode);
1576 if (!empty($dates)) {
1fc22ffa 1577 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], '%Y%m%d'));
1578 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], '%Y%m%d'));
668ddfc2
EM
1579 }
1580
1581 if (!empty($membershipContribution)) {
1582 // update recurring id for membership record
1583 CRM_Member_BAO_Membership::updateRecurMembership($membership, $membershipContribution);
8e8d287f 1584 // Next line is probably redundant. Checksprevent it happening twice.
668ddfc2
EM
1585 CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
1586 }
1587 }
1588 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1589 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
e894942a
WA
1590 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id == $priceFieldOp['membership_type_id']) {
1591 $membershipOb = $membership;
668ddfc2
EM
1592 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
1593 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
1594 }
1595 else {
1596 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1597 }
1598 }
1599 $form->_values['lineItem'] = $form->_lineItem;
1600 $form->assign('lineItem', $form->_lineItem);
1601 }
1602 }
1603
1604 if (!empty($errors)) {
1605 $message = $this->compileErrorMessage($errors);
1606 throw new CRM_Core_Exception($message);
1607 }
1608 $form->_params['createdMembershipIDs'] = array();
1609
1610 // CRM-7851 - Moved after processing Payment Errors
1611 //@todo - the reasoning for this being here seems a little outdated
28da8ecd
WA
1612 CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $membership->id, 'Membership');
1613 $form->_params['createdMembershipIDs'][] = $membership->id;
1614
e894942a 1615 if ($membership) {
668ddfc2 1616 //presumably this is only relevant for exactly 1 membership
28da8ecd 1617 $form->_params['membershipID'] = $membership->id;
668ddfc2
EM
1618 }
1619
1620 //CRM-15232: Check if membership is created and on the basis of it use
1621 //membership receipt template to send payment receipt
e894942a 1622 if ($membership) {
668ddfc2
EM
1623 $form->_values['isMembership'] = TRUE;
1624 }
82583880
EM
1625 if (isset($membershipContributionID)) {
1626 $form->_values['contribution_id'] = $membershipContributionID;
1627 }
a506739a 1628
1fc22ffa 1629 if (empty($form->_params['is_pay_later']) && $form->_paymentProcessor) {
a506739a 1630 // the is_monetary concept probably should be deprecated as it can be calculated from
1631 // the existence of 'amount' & seems fragile.
668ddfc2
EM
1632 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1633 // call postProcess hook before leaving
1634 $form->postProcessHook();
668ddfc2 1635 }
a506739a 1636
82583880 1637 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
fe3dbce1 1638 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1639 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1640 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1641 $paymentParams = array_merge($form->_params, array('contributionID' => $form->_values['contribution_other_id']));
b43ed44b
PN
1642
1643 // CRM-19792 : set necessary fields for payment processor
1644 CRM_Core_Payment_Form::mapParams($form->_bltID, $paymentParams, $paymentParams, TRUE);
1645
fe3dbce1 1646 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
63137f3a 1647 $paymentResults[] = array('contribution_id' => $paymentResult['contribution']->id, 'result' => $paymentActionResult);
668ddfc2
EM
1648 // Do not send an email if Recurring transaction is done via Direct Mode
1649 // Email will we sent when the IPN is received.
63137f3a 1650 foreach ($paymentResults as $result) {
7c864699
TL
1651 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1652 if ($result['contribution_id']) {
1653 $this->completeTransaction($result['result'], $result['contribution_id']);
1654 }
63137f3a 1655 }
668ddfc2
EM
1656 return;
1657 }
1658
1fc22ffa 1659 $emailValues = array_merge($membershipParams, $form->_values);
1660 $emailValues['membership_assign'] = 1;
858f7096 1661 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1662 if ($totalAmount == 0) {
1663 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1664 $emailValues['useForMember'] = 0;
858f7096 1665 $emailValues['amount'] = 0;
036c6315 1666
1667 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1668 // also it reset any payment processor selection result into pending free membership
1669 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
bd53b1b9 1670 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
036c6315 1671 $paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor', $this->_values));
1672 if (empty($form->_paymentProcessor) && !empty($paymentProcessorIDs)) {
1673 $this->_paymentProcessor['id'] = $paymentProcessorIDs[0];
1674 }
1675 $result = array('payment_status_id' => 1, 'contribution' => $membershipContribution);
1676 $this->completeTransaction($result, $result['contribution']->id);
1677 }
858f7096 1678 }
1fc22ffa 1679
668ddfc2 1680 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
858f7096 1681 $emailValues,
668ddfc2
EM
1682 $isTest, FALSE,
1683 $includeFieldTypes
1684 );
1685 }
1686
1687 /**
1688 * Turn array of errors into message string.
1689 *
1690 * @param array $errors
1691 *
1692 * @return string
1693 */
1694 protected function compileErrorMessage($errors) {
1695 foreach ($errors as $error) {
1696 if (is_string($error)) {
1697 $message[] = $error;
1698 }
1699 }
1700 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1701 }
1702
1703 /**
1704 * Where a second separate financial transaction is supported we will process it here.
1705 *
1706 * @param int $contactID
1707 * @param CRM_Contribute_Form_Contribution_Confirm $form
1708 * @param array $tempParams
1709 * @param bool $isTest
1710 * @param array $lineItems
1711 * @param $minimumFee
1712 * @param int $financialTypeID
1713 *
1714 * @throws CRM_Core_Exception
1715 * @throws Exception
1716 * @return CRM_Contribute_BAO_Contribution
1717 */
1718 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1719 $financialTypeID) {
1720 $financialType = new CRM_Financial_DAO_FinancialType();
1721 $financialType->id = $financialTypeID;
1722 $financialType->find(TRUE);
1723 $tempParams['amount'] = $minimumFee;
1724 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
449f4c90 1725 $isRecur = CRM_Utils_Array::value('is_recur', $tempParams);
668ddfc2 1726
668ddfc2
EM
1727 //assign receive date when separate membership payment
1728 //and contribution amount not selected.
1729 if ($form->_amount == 0) {
1730 $now = date('YmdHis');
1731 $form->_params['receive_date'] = $now;
1732 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
1733 $form->set('params', $form->_params);
1734 $form->assign('receive_date', $receiveDate);
1735 }
1736
668ddfc2 1737 $form->set('membership_amount', $minimumFee);
668ddfc2
EM
1738 $form->assign('membership_amount', $minimumFee);
1739
1740 // we don't need to create the user twice, so lets disable cms_create_account
1741 // irrespective of the value, CRM-2888
1742 $tempParams['cms_create_account'] = 0;
1743
668ddfc2
EM
1744 //set this variable as we are not creating pledge for
1745 //separate membership payment contribution.
1746 //so for differentiating membership contribution from
1747 //main contribution.
1748 $form->_params['separate_membership_payment'] = 1;
3febe800 1749 $contributionParams = array(
1750 'contact_id' => $contactID,
1751 'line_item' => $lineItems,
1752 'is_test' => $isTest,
1753 'campaign_id' => CRM_Utils_Array::value('campaign_id', $tempParams, CRM_Utils_Array::value('campaign_id',
1754 $form->_values)),
1755 'contribution_page_id' => $form->_id,
1756 'source' => CRM_Utils_Array::value('source', $tempParams, CRM_Utils_Array::value('description', $tempParams)),
1757 );
1758 $isMonetary = !empty($form->_values['is_monetary']);
1759 if ($isMonetary) {
1760 if (empty($paymentParams['is_pay_later'])) {
f3a63d1e 1761 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
3febe800 1762 }
1763 }
b43ed44b
PN
1764
1765 // CRM-19792 : set necessary fields for payment processor
1766 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $tempParams, TRUE);
1767
668ddfc2
EM
1768 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
1769 $tempParams,
0193ebdb 1770 $tempParams,
3febe800 1771 $contributionParams,
668ddfc2 1772 $financialType,
668ddfc2 1773 TRUE,
449f4c90 1774 $form->_bltID,
1775 $isRecur
668ddfc2 1776 );
0193ebdb 1777
4ae9c8ac 1778 $result = array();
0193ebdb 1779 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
1780 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1781 // now we compensate here.
1782 if (empty($form->_paymentProcessor['object'])) {
1783 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1784 }
1785 else {
1786 $payment = $form->_paymentProcessor['object'];
1787 }
1788 $result = $payment->doPayment($tempParams, 'contribute');
1789 $form->set('membership_trx_id', $result['trxn_id']);
1790 $form->assign('membership_trx_id', $result['trxn_id']);
0193ebdb 1791 }
1792
63137f3a 1793 return array($membershipContribution, $result);
668ddfc2
EM
1794 }
1795
1796 /**
8bc79dfc
EM
1797 * Is the payment a pending payment.
1798 *
1799 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1800 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1801 *
8bc79dfc
EM
1802 * @return bool
1803 */
1804 protected function getIsPending() {
0f2b049e 1805 // The concept of contributeMode is deprecated.
1806 // the is_monetary concept probably should be too as it can be calculated from
1807 // the existence of 'amount' & seems fragile.
8bc79dfc
EM
1808 if (((isset($this->_contributeMode)) || !empty
1809 ($this->_params['is_pay_later'])
1810 ) &&
1811 (($this->_values['is_monetary'] && $this->_amount > 0.0))
1812 ) {
1813 return TRUE;
1814 }
1815 return FALSE;
1816 }
1817
fb49fa48 1818 /**
5e4f7f74 1819 * Are we going to do 2 financial transactions.
fb49fa48 1820 *
5e4f7f74
EM
1821 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1822 * contribution
1823 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
fb49fa48 1824 *
014c4014 1825 * @param int $formID
fb49fa48
EM
1826 * @param bool $amountBlockActiveOnForm
1827 *
1828 * @return bool
1829 */
1830 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1831 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1832 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1833 return TRUE;
1834 }
1835 return FALSE;
1836 }
df6c4f28
EM
1837
1838 /**
5e4f7f74
EM
1839 * This function sets the fields.
1840 *
df6c4f28
EM
1841 * - $this->_params['amount_level']
1842 * - $this->_params['selectMembership']
1843 * And under certain circumstances sets
1844 * $this->_params['amount'] = null;
1845 *
100fef9d 1846 * @param int $priceSetID
df6c4f28
EM
1847 */
1848 public function setFormAmountFields($priceSetID) {
1849 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1850 $priceField = new CRM_Price_DAO_PriceField();
1851 $priceField->price_set_id = $priceSetID;
1852 $priceField->orderBy('weight');
1853 $priceField->find();
06b4ee3e 1854 $paramWeDoNotUnderstand = NULL;
df6c4f28
EM
1855
1856 while ($priceField->fetch()) {
df6c4f28
EM
1857 if ($priceField->name == "contribution_amount") {
1858 $paramWeDoNotUnderstand = $priceField->id;
1859 }
1860 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1861 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
c039f658 1862 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1863 // function to get correct amount level consistently. Remove setting of the amount level in
1864 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1865 // to cover all variants.
df6c4f28
EM
1866 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1867 $this->_params["price_{$priceField->id}"], 'label');
1868 }
1869 if ($priceField->name == "membership_amount") {
1870 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1871 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1872 }
5e4f7f74
EM
1873 }
1874 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1875 // as membership amount.
df6c4f28
EM
1876 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1877 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1878 // so we should merge them together
1879 // the quick config seems like a red-herring - if this is about a separate membership payment then there
f64a217a 1880 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
df6c4f28
EM
1881 elseif (
1882 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1883 && !empty($this->_values['fee'][$priceField->id])
1884 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1885 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1886 && empty($this->_params["price_{$priceField->id}"])
1887 ) {
a13f3d8c 1888 $this->_params['amount'] = NULL;
df6c4f28
EM
1889 }
1890
1891 // Fix for CRM-14375 - If we are using separate payments and "no
1892 // thank you" is selected for the additional contribution, set
1893 // contribution amount to be null, so that it will not show
1894 // contribution amount same as membership amount.
1895 //@todo - merge with section above
1896 if ($this->_membershipBlock['is_separate_payment']
3c0201c9 1897 && !empty($this->_values['fee'][$priceField->id])
df6c4f28
EM
1898 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1899 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1900 ) {
a13f3d8c 1901 $this->_params['amount'] = NULL;
df6c4f28
EM
1902 }
1903 }
1904 }
be26f3e0 1905
03110609 1906 /**
5e4f7f74
EM
1907 * Submit function.
1908 *
03110609
EM
1909 * @param array $params
1910 *
1911 * @throws CiviCRM_API3_Exception
1912 */
00be9182 1913 public static function submit($params) {
be26f3e0
EM
1914 $form = new CRM_Contribute_Form_Contribution_Confirm();
1915 $form->_id = $params['id'];
75637f22 1916
f64a217a
EM
1917 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1918 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
be26f3e0
EM
1919 //this way the mocked up controller ignores the session stuff
1920 $_SERVER['REQUEST_METHOD'] = 'GET';
1921 $form->controller = new CRM_Contribute_Controller_Contribution();
1922 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1923 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
f64a217a 1924 $form->_amount = $params['amount'];
870156d6 1925 // hack these in for test support.
1926 $form->_fields['billing_first_name'] = 1;
1927 $form->_fields['billing_last_name'] = 1;
dccd9f4f
ERL
1928 // CRM-18854 - Set form values to allow pledge to be created for api test.
1929 if (CRM_Utils_Array::value('pledge_block_id', $params)) {
3044f490 1930 $form->_values['pledge_id'] = CRM_Utils_Array::value('pledge_id', $params, NULL);
dccd9f4f
ERL
1931 $form->_values['pledge_block_id'] = $params['pledge_block_id'];
1932 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($params['id']);
1933 $form->_values['max_reminders'] = $pledgeBlock['max_reminders'];
1934 $form->_values['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
1935 $form->_values['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
1936 $form->_values['is_email_receipt'] = FALSE;
1937 }
be26f3e0
EM
1938 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1939 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
f64a217a
EM
1940 $priceSetFields = reset($priceFields);
1941 $form->_values['fee'] = $priceSetFields['fields'];
5624f515 1942 $form->_priceSetId = $priceSetID;
be26f3e0 1943 $form->setFormAmountFields($priceSetID);
e02d7e96
EM
1944 if (!empty($params['payment_processor_id'])) {
1945 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array(
1946 'id' => $params['payment_processor_id'],
1947 ));
0f2b049e 1948 // The concept of contributeMode is deprecated as is the billing_mode concept.
a13f3d8c 1949 if ($form->_paymentProcessor['billing_mode'] == 1) {
e6fa4056
EM
1950 $form->_contributeMode = 'direct';
1951 }
1952 else {
1953 $form->_contributeMode = 'notify';
1954 }
d25e4224 1955 }
07102c2c 1956 else {
e02d7e96 1957 $form->_params['payment_processor_id'] = 0;
07102c2c 1958 }
65e172a3 1959
be26f3e0
EM
1960 $priceFields = $priceFields[$priceSetID]['fields'];
1961 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1962 $form->_lineItem = array($priceSetID => $lineItems);
65e172a3 1963 $membershipPriceFieldIDs = array();
1964 foreach ((array) $lineItems as $lineItem) {
1965 if (!empty($lineItem['membership_type_id'])) {
1966 $form->set('useForMember', 1);
1967 $form->_useForMember = 1;
1968 $membershipPriceFieldIDs['id'] = $priceSetID;
1969 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
1970 }
1971 }
1972 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
75637f22 1973 $form->processFormSubmission(CRM_Utils_Array::value('contact_id', $params));
be26f3e0
EM
1974 }
1975
1976 /**
ceb9fecb
EM
1977 * Helper function for static submit function.
1978 *
1979 * Set relevant params - help us to build up an array that we can pass in.
5e4f7f74 1980 *
100fef9d 1981 * @param int $id
be26f3e0
EM
1982 * @param array $params
1983 *
1984 * @return array
1985 * @throws CiviCRM_API3_Exception
1986 */
00be9182 1987 public static function getFormParams($id, array $params) {
a13f3d8c 1988 if (!isset($params['is_pay_later'])) {
e02d7e96 1989 if (!empty($params['payment_processor_id'])) {
d25e4224
DG
1990 $params['is_pay_later'] = 0;
1991 }
1992 else {
1993 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
a13f3d8c 1994 'id' => $id,
21dfd5f5 1995 'return' => 'is_pay_later',
a13f3d8c 1996 ));
d25e4224 1997 }
be26f3e0 1998 }
a13f3d8c 1999 if (empty($params['price_set_id'])) {
be26f3e0
EM
2000 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
2001 }
2002 return $params;
2003 }
96025800 2004
75637f22
EM
2005 /**
2006 * Post form submission handling.
2007 *
2008 * This is also called from the test suite.
2009 *
2010 * @param int $contactID
2011 *
2012 * @return array
2013 */
2014 protected function processFormSubmission($contactID) {
858f7096 2015 if (!isset($this->_params['payment_processor_id'])) {
2016 // If there is no processor we are using the pay-later manual pseudo-processor.
2017 // (note it might make sense to make this a row in the processor table in the db).
2018 $this->_params['payment_processor_id'] = 0;
2019 }
036c6315 2020 if (isset($this->_params['payment_processor_id']) && $this->_params['payment_processor_id'] === 0) {
75637f22
EM
2021 $this->_params['is_pay_later'] = $isPayLater = TRUE;
2022 }
58466af1 2023
2024 if (!empty($this->_ccid)) {
2025 $this->_params['contribution_id'] = $this->_ccid;
2026 }
75637f22
EM
2027 // add a description field at the very beginning
2028 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
2029
2030 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values);
2031
2032 // fix currency ID
2033 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
2034
dccd9f4f 2035 // CRM-18854
cdc7779f 2036 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 2037 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
d9a9ea3b
E
2038 if (CRM_Utils_Array::value('start_date', $this->_params) || !CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)
2039 || !CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
dccd9f4f
ERL
2040 $pledgeStartDate = CRM_Utils_Array::value('start_date', $this->_params, NULL);
2041 $this->_params['receive_date'] = CRM_Pledge_BAO_Pledge::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2042 $recurParams = CRM_Pledge_BAO_Pledge::buildRecurParams($this->_params);
2043 $this->_params = array_merge($this->_params, $recurParams);
2044 }
2045 }
2046
75637f22
EM
2047 //carry payment processor id.
2048 if (CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
2049 $this->_params['payment_processor_id'] = $this->_paymentProcessor['id'];
2050 }
f85b8063
KJ
2051
2052 $premiumParams = $membershipParams = $params = $this->_params;
75637f22
EM
2053 if (!empty($params['image_URL'])) {
2054 CRM_Contact_BAO_Contact::processImageParams($params);
2055 }
f85b8063 2056
75637f22
EM
2057 $fields = array('email-Primary' => 1);
2058
2059 // get the add to groups
2060 $addToGroups = array();
2061
2062 // now set the values for the billing location.
2063 foreach ($this->_fields as $name => $value) {
2064 $fields[$name] = 1;
2065
2066 // get the add to groups for uf fields
2067 if (!empty($value['add_to_group_id'])) {
2068 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2069 }
2070 }
2071
bddc8a28 2072 $fields = $this->formatParamsForPaymentProcessor($fields);
75637f22
EM
2073
2074 // billing email address
2075 $fields["email-{$this->_bltID}"] = 1;
2076
75637f22
EM
2077 // if onbehalf-of-organization contribution, take out
2078 // organization params in a separate variable, to make sure
2079 // normal behavior is continued. And use that variable to
2080 // process on-behalf-of functionality.
2f44fc96 2081 if (!empty($this->_values['onbehalf_profile_id']) && empty($this->_ccid)) {
75637f22
EM
2082 $behalfOrganization = array();
2083 $orgFields = array('organization_name', 'organization_id', 'org_option');
2084 foreach ($orgFields as $fld) {
2085 if (array_key_exists($fld, $params)) {
2086 $behalfOrganization[$fld] = $params[$fld];
2087 unset($params[$fld]);
2088 }
2089 }
2090
2091 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2092 foreach ($params['onbehalf'] as $fld => $values) {
2093 if (strstr($fld, 'custom_')) {
2094 $behalfOrganization[$fld] = $values;
2095 }
2096 elseif (!(strstr($fld, '-'))) {
2097 if (in_array($fld, array(
2098 'contribution_campaign_id',
2099 'member_campaign_id',
2100 ))) {
2101 $fld = 'campaign_id';
2102 }
2103 else {
2104 $behalfOrganization[$fld] = $values;
2105 }
2106 $this->_params[$fld] = $values;
2107 }
2108 }
2109 }
2110
2111 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2112 foreach ($params['onbehalf_location'] as $block => $vals) {
2113 //fix for custom data (of type checkbox, multi-select)
2114 if (substr($block, 0, 7) == 'custom_') {
2115 continue;
2116 }
2117 // fix the index of block elements
2118 if (is_array($vals)) {
2119 foreach ($vals as $key => $val) {
2120 //dont adjust the index of address block as
2121 //it's index is WRT to location type
2122 $newKey = ($block == 'address') ? $key : ++$key;
2123 $behalfOrganization[$block][$newKey] = $val;
2124 }
2125 }
2126 }
2127 unset($params['onbehalf_location']);
2128 }
2129 if (!empty($params['onbehalf[image_URL]'])) {
2130 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2131 }
2132 }
2133
2134 // check for profile double opt-in and get groups to be subscribed
2135 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
2136
2137 // since we are directly adding contact to group lets unset it from mailing
2138 if (!empty($addToGroups)) {
2139 foreach ($addToGroups as $groupId) {
2140 if (isset($subscribeGroupIds[$groupId])) {
2141 unset($subscribeGroupIds[$groupId]);
2142 }
2143 }
2144 }
2145
2146 foreach ($addToGroups as $k) {
2147 if (array_key_exists($k, $subscribeGroupIds)) {
2148 unset($addToGroups[$k]);
2149 }
2150 }
2151
2152 if (empty($contactID)) {
2153 $dupeParams = $params;
2154 if (!empty($dupeParams['onbehalf'])) {
2155 unset($dupeParams['onbehalf']);
2156 }
2157 if (!empty($dupeParams['honor'])) {
2158 unset($dupeParams['honor']);
2159 }
2160
03b40a7b 2161 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', array(), FALSE);
75637f22
EM
2162
2163 // Fetch default greeting id's if creating a contact
2164 if (!$contactID) {
2165 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
2166 if (!isset($params[$greeting])) {
2167 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
2168 }
2169 }
2170 }
2171 $contactType = NULL;
2172 }
2173 else {
2174 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2175 }
2176 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
2177 $params,
2178 $fields,
2179 $contactID,
2180 $addToGroups,
2181 NULL,
2182 $contactType,
2183 TRUE
2184 );
2185
2186 // Make the contact ID associated with the contribution available at the Class level.
2187 // Also make available to the session.
2188 //@todo consider handling this in $this->getContactID();
2189 $this->set('contactID', $contactID);
2190 $this->_contactID = $contactID;
2191
2192 //get email primary first if exist
2193 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
2194 if (!$subscriptionEmail['email']) {
2195 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
2196 }
2197 // subscribing contact to groups
2198 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2199 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2200 }
2201
2202 // If onbehalf-of-organization contribution / signup, add organization
2203 // and it's location.
a9653117 2204 if (isset($this->_values['onbehalf_profile_id']) &&
2205 isset($behalfOrganization['organization_name']) &&
2206 ($this->_values['is_for_organization'] == 2 ||
2207 !empty($this->_params['is_for_organization'])
2208 )
2209 ) {
75637f22
EM
2210 $ufFields = array();
2211 foreach ($this->_fields['onbehalf'] as $name => $value) {
2212 $ufFields[$name] = 1;
2213 }
2214 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
2215 $this->_params, $ufFields
2216 );
2217 }
2218 elseif (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
2219 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2220 // store current user id as related contact for later use for mailing / activity..
2221 $this->_values['related_contact'] = $contactID;
2222 $this->_params['related_contact'] = $contactID;
2223 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2224 $contactID = $this->_membershipContactID;
2225 }
2226
2227 // lets store the contactID in the session
2228 // for things like tell a friend
2229 $session = CRM_Core_Session::singleton();
2230 if (!$session->get('userID')) {
2231 $session->set('transaction.userID', $contactID);
2232 }
2233 else {
2234 $session->set('transaction.userID', NULL);
2235 }
2236
2237 $this->_useForMember = $this->get('useForMember');
2238
2239 // store the fact that this is a membership and membership type is selected
75637f22
EM
2240 if ((!empty($membershipParams['selectMembership']) &&
2241 $membershipParams['selectMembership'] != 'no_thanks'
2242 ) ||
2243 $this->_useForMember
2244 ) {
75637f22
EM
2245 if (!$this->_useForMember) {
2246 $this->assign('membership_assign', TRUE);
2247 $this->set('membershipTypeID', $this->_params['selectMembership']);
2248 }
2249
2250 if ($this->_action & CRM_Core_Action::PREVIEW) {
2251 $membershipParams['is_test'] = 1;
2252 }
2253 if ($this->_params['is_pay_later']) {
2254 $membershipParams['is_pay_later'] = 1;
2255 }
75637f22 2256
2dc204ea 2257 if (isset($this->_params['onbehalf_contact_id'])) {
2258 $membershipParams['onbehalf_contact_id'] = $this->_params['onbehalf_contact_id'];
2259 }
75637f22
EM
2260 //inherit campaign from contribution page.
2261 if (!array_key_exists('campaign_id', $membershipParams)) {
2262 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
2263 }
2264
7dd9ca37 2265 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
f2bca231 2266 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem);
75637f22
EM
2267 }
2268 else {
2269 // at this point we've created a contact and stored its address etc
2270 // all the payment processors expect the name and address to be in the
2271 // so we copy stuff over to first_name etc.
2272 $paymentParams = $this->_params;
f2bca231 2273 // Make it explict that we are letting the processConfirm function figure out the line items.
2274 $paymentParams['skipLineItem'] = 0;
75637f22 2275
1659de20
PN
2276 if (!isset($paymentParams['line_item'])) {
2277 $paymentParams['line_item'] = $this->_lineItem;
2278 }
2279
75637f22
EM
2280 if (!empty($paymentParams['onbehalf']) &&
2281 is_array($paymentParams['onbehalf'])
2282 ) {
2283 foreach ($paymentParams['onbehalf'] as $key => $value) {
2284 if (strstr($key, 'custom_')) {
2285 $this->_params[$key] = $value;
2286 }
2287 }
75637f22 2288 }
10490499 2289
a8a4259e 2290 $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
5fb28746 2291 $contactID,
46763692 2292 $this->wrangleFinancialTypeID($this->_values['financial_type_id']),
449f4c90 2293 ($this->_mode == 'test') ? 1 : 0,
10490499 2294 CRM_Utils_Array::value('is_recur', $paymentParams)
75637f22 2295 );
82583880 2296
0193ebdb 2297 if (empty($result['is_payment_failure'])) {
2298 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2299 $this->postProcessPremium($premiumParams, $result['contribution']);
2300 }
2301 if (!empty($result['contribution'])) {
2302 // Not quite sure why it would be empty at this stage but tests show it can be ... at least in tests.
2303 $this->completeTransaction($result, $result['contribution']->id);
a8a4259e
EM
2304 }
2305 return $result;
75637f22
EM
2306 }
2307 }
2308
7dd9ca37
EM
2309 /**
2310 * Membership processing section.
2311 *
2312 * This is in a separate function as part of a move towards refactoring.
2313 *
2314 * @param int $contactID
2315 * @param array $membershipParams
2316 * @param array $premiumParams
f2bca231 2317 * @param array $formLineItems
7dd9ca37 2318 */
f2bca231 2319 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
0d9ff2d4 2320 // This could be set by a hook.
2321 if (!empty($this->_params['installments'])) {
2322 $membershipParams['installments'] = $this->_params['installments'];
2323 }
7dd9ca37
EM
2324 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2325 if (isset($this->_params['related_contact'])) {
2326 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
2327 }
2328 else {
2329 $membershipParams['cms_contactID'] = $contactID;
2330 }
2331
2332 if (!empty($membershipParams['onbehalf']) &&
2333 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2334 ) {
2335 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2336 }
2337
2338 $customFieldsFormatted = $fieldTypes = array();
2339 if (!empty($membershipParams['onbehalf']) &&
2340 is_array($membershipParams['onbehalf'])
2341 ) {
2342 foreach ($membershipParams['onbehalf'] as $key => $value) {
2343 if (strstr($key, 'custom_')) {
2344 $customFieldId = explode('_', $key);
2345 CRM_Core_BAO_CustomField::formatCustomField(
2346 $customFieldId[1],
2347 $customFieldsFormatted,
2348 $value,
2349 'Membership',
2350 NULL,
2351 $contactID
2352 );
2353 }
2354 }
2355 $fieldTypes = array('Contact', 'Organization', 'Membership');
2356 }
2357
2358 $priceFieldIds = $this->get('memberPriceFieldIDS');
2359
2360 if (!empty($priceFieldIds)) {
65e172a3 2361 $financialTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
7dd9ca37
EM
2362 unset($priceFieldIds['id']);
2363 $membershipTypeIds = array();
2364 $membershipTypeTerms = array();
2365 foreach ($priceFieldIds as $priceFieldId) {
2366 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
2367 $membershipTypeIds[] = $id;
2368 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
2369 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
2370 $term = 1;
2371 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
2372 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
2373 }
2374 else {
2375 $membershipTypeTerms[$id] = 1;
2376 }
2377 }
2378 }
2379 $membershipParams['selectMembership'] = $membershipTypeIds;
65e172a3 2380 $membershipParams['financial_type_id'] = $financialTypeID;
7dd9ca37
EM
2381 $membershipParams['types_terms'] = $membershipTypeTerms;
2382 }
2383 if (!empty($membershipParams['selectMembership'])) {
2384 // CRM-12233
f2bca231 2385 $membershipLineItems = $formLineItems;
7dd9ca37 2386 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
f2bca231 2387 $membershipLineItems = array();
7dd9ca37
EM
2388 foreach ($this->_values['fee'] as $key => $feeValues) {
2389 if ($feeValues['name'] == 'membership_amount') {
2390 $fieldId = $this->_params['price_' . $key];
2391 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
2392 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
2393 break;
2394 }
2395 }
2396 }
4b6c8c1e 2397 try {
f2bca231 2398 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
4b6c8c1e 2399 }
2400 catch (CRM_Core_Exception $e) {
2401 CRM_Core_Session::singleton()->setStatus($e->getMessage());
2402 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2403 }
7dd9ca37
EM
2404 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
2405 // we need to explicitly create a CMS user in case of free memberships
2406 // since it is done under processConfirm for paid memberships
2407 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
2408 $membershipParams['cms_contactID'],
2409 'email-' . $this->_bltID
2410 );
2411 }
2412 }
2413 }
2414
0193ebdb 2415 /**
2416 * Complete transaction if payment has been processed.
2417 *
2418 * Check the result for a success outcome & if paid then complete the transaction.
2419 *
2420 * Completing will trigger update of related entities and emails.
2421 *
2422 * @param array $result
2423 * @param int $contributionID
2424 *
ec7e3954
E
2425 * @throws \CiviCRM_API3_Exception
2426 * @throws \Exception
0193ebdb 2427 */
2428 protected function completeTransaction($result, $contributionID) {
2429 if (CRM_Utils_Array::value('payment_status_id', $result) == 1) {
2430 try {
2431 civicrm_api3('contribution', 'completetransaction', array(
2432 'id' => $contributionID,
2433 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result),
2434 'payment_processor_id' => $this->_paymentProcessor['id'],
2435 'is_transactional' => FALSE,
2436 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
dccd9f4f 2437 'receive_date' => CRM_Utils_Array::value('receive_date', $result),
0193ebdb 2438 )
2439 );
2440 }
2441 catch (CiviCRM_API3_Exception $e) {
2442 if ($e->getErrorCode() != 'contribution_completed') {
2443 throw new CRM_Core_Exception('Failed to update contribution in database');
2444 }
2445 }
2446 }
2447 }
2448
6a488035 2449}