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