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