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