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