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