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