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