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