Merge branch 'master' of github.com:webaccess/civicrm-core into sales-tax
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Confirm.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * form to process actions on the group aspect of Custom Data
38 */
39 class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
40
41 /**
42 * the id of the contact associated with this contribution
43 *
44 * @var int
45 * @public
46 */
47 public $_contactID;
48
49
50 /**
51 * The id of the contribution object that is created when the form is submitted
52 *
53 * @var int
54 * @public
55 */
56 public $_contributionID;
57
58 /**
59 * Set the parameters to be passed to contribution create function
60 *
61 * @param array $params
62 * @param integer $contactID
63 * @param $financialTypeID
64 * @param $online
65 * @param $contributionPageId
66 * @param $nonDeductibleAmount
67 * @param $campaignId
68 *
69 * @param $isMonetary
70 *
71 * @param $pending
72 * @param $paymentProcessorOutcome
73 * @param $receiptDate
74 *
75 * @param $recurringContributionID
76 * @param $isTest
77 *
78 * @param $addressID
79 *
80 * @param $softCreditToID
81 *
82 * @param $lineItems
83 *
84 * @internal param $financialType
85 * @return array
86 */
87 public static function getContributionParams($params, $contactID, $financialTypeID, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending,
88 $paymentProcessorOutcome, $receiptDate, $recurringContributionID, $isTest, $addressID, $softCreditToID, $lineItems)
89 {
90 $contributionParams = array(
91 'contact_id' => $contactID,
92 'financial_type_id' => $financialTypeID,
93 'contribution_page_id' => $contributionPageId,
94 'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
95 'non_deductible_amount' => $nonDeductibleAmount,
96 'total_amount' => $params['amount'],
97 'tax_amount' => CRM_Utils_Array::value('tax_amount', $params),
98 'amount_level' => CRM_Utils_Array::value('amount_level', $params),
99 'invoice_id' => $params['invoiceID'],
100 'currency' => $params['currencyID'],
101 'source' =>
102 (!$online || !empty($params['source'])) ?
103 CRM_Utils_Array::value('source', $params) :
104 CRM_Utils_Array::value('description', $params),
105 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
106 //configure cancel reason, cancel date and thankyou date
107 //from 'contribution' type profile if included
108 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
109 'cancel_date' =>
110 isset($params['cancel_date']) ?
111 CRM_Utils_Date::format($params['cancel_date']) :
112 NULL,
113 'thankyou_date' =>
114 isset($params['thankyou_date']) ?
115 CRM_Utils_Date::format($params['thankyou_date']) :
116 NULL,
117 'campaign_id' => $campaignId,
118 'is_test' => $isTest,
119 'address_id' => $addressID,
120 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
121 'soft_credit_to' => $softCreditToID,
122 'line_item' => $lineItems,
123 'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0)
124 );
125 if (!$online && isset($params['thankyou_date'])) {
126 $contributionParam['thankyou_date'] = $params['thankyou_date'];
127 }
128 if (!$online || $isMonetary) {
129 if (empty($params['is_pay_later'])) {
130 $contributionParams['payment_instrument_id'] = 1;
131 }
132 }
133 if (!$pending && $paymentProcessorOutcome) {
134 $contributionParams += array(
135 'fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome),
136 'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']),
137 'trxn_id' => $paymentProcessorOutcome['trxn_id'],
138 'receipt_date' => $receiptDate,
139 // also add financial_trxn details as part of fix for CRM-4724
140 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome),
141 'payment_processor' => CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome),
142 );
143 }
144
145 // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
146 $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
147 $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
148
149 if ($recurringContributionID) {
150 $contributionParams['contribution_recur_id'] = $recurringContributionID;
151 }
152
153 $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
154 if (isset($contributionParams['invoice_id'])) {
155 $contributionParams['id'] = CRM_Core_DAO::getFieldValue(
156 'CRM_Contribute_DAO_Contribution',
157 $contributionParams['invoice_id'],
158 'id',
159 'invoice_id'
160 );
161 }
162
163 return $contributionParams;
164 }
165
166 /**
167 * Function to set variables up before form is built
168 *
169 * @return void
170 * @access public
171 */
172 public function preProcess() {
173 $config = CRM_Core_Config::singleton();
174 parent::preProcess();
175
176 // lineItem isn't set until Register postProcess
177 $this->_lineItem = $this->get('lineItem');
178 $this->_paymentProcessor = $this->get('paymentProcessor');
179
180 if ($this->_contributeMode == 'express') {
181 // rfp == redirect from paypal
182 $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
183 CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'
184 );
185 if ($rfp) {
186 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
187 $expressParams = $payment->getExpressCheckoutDetails($this->get('token'));
188
189 $this->_params['payer'] = $expressParams['payer'];
190 $this->_params['payer_id'] = $expressParams['payer_id'];
191 $this->_params['payer_status'] = $expressParams['payer_status'];
192
193 CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE);
194
195 // fix state and country id if present
196 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
197 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
198 }
199 if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) {
200 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
201 }
202
203 // set a few other parameters for PayPal
204 $this->_params['token'] = $this->get('token');
205
206 $this->_params['amount'] = $this->get('amount');
207
208 if (!empty($this->_membershipBlock)){
209 $this->_params['selectMembership'] = $this->get('selectMembership');
210 }
211 // we use this here to incorporate any changes made by folks in hooks
212 $this->_params['currencyID'] = $config->defaultCurrency;
213
214 $this->_params['payment_action'] = 'Sale';
215
216 // also merge all the other values from the profile fields
217 $values = $this->controller->exportValues('Main');
218 $skipFields = array(
219 'amount', 'amount_other',
220 "billing_street_address-{$this->_bltID}",
221 "billing_city-{$this->_bltID}",
222 "billing_state_province_id-{$this->_bltID}",
223 "billing_postal_code-{$this->_bltID}",
224 "billing_country_id-{$this->_bltID}",
225 );
226 foreach ($values as $name => $value) {
227 // skip amount field
228 if (!in_array($name, $skipFields)) {
229 $this->_params[$name] = $value;
230 }
231 }
232 $this->set('getExpressCheckoutDetails', $this->_params);
233 }
234 else {
235 $this->_params = $this->get('getExpressCheckoutDetails');
236 }
237 }
238 else {
239 $this->_params = $this->controller->exportValues('Main');
240
241 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
242 $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
243 }
244 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
245 $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
246 }
247
248 if (isset($this->_params['credit_card_exp_date'])) {
249 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
250 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
251 }
252
253 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
254 $this->_params['amount'] = $this->get('amount');
255 $this->_params['tax_amount'] = $this->get('tax_amount');
256
257 $this->_useForMember = $this->get('useForMember');
258
259 if (isset($this->_params['amount'])) {
260 $this->setFormAmountFields($this->_params['priceSetId']);
261 }
262 $this->_params['currencyID'] = $config->defaultCurrency;
263 $this->_params['payment_action'] = 'Sale';
264 }
265
266 $this->_params['is_pay_later'] = $this->get('is_pay_later');
267 $this->assign('is_pay_later', $this->_params['is_pay_later']);
268 if ($this->_params['is_pay_later']) {
269 $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
270 }
271 // if onbehalf-of-organization
272 if (!empty($this->_params['hidden_onbehalf_profile'])) {
273 // CRM-15182
274 if (empty($this->_params['org_option']) && empty($this->_params['organization_id'])) {
275 if (!empty($this->_params['onbehalfof_id'])) {
276 $this->_params['organization_id'] = $this->_params['onbehalfof_id'];
277 }
278 else {
279 $this->_params['organization_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_params['onbehalf']['organization_name'], 'id', 'display_name');
280 }
281 }
282
283 $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
284 $addressBlocks = array(
285 'street_address', 'city', 'state_province',
286 'postal_code', 'country', 'supplemental_address_1',
287 'supplemental_address_2', 'supplemental_address_3',
288 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name',
289 );
290
291 $blocks = array('email', 'phone', 'im', 'url', 'openid');
292 foreach ($this->_params['onbehalf'] as $loc => $value) {
293 $field = $typeId = NULL;
294 if (strstr($loc, '-')) {
295 list($field, $locType) = explode('-', $loc);
296 }
297
298 if (in_array($field, $addressBlocks)) {
299 if ($locType == 'Primary') {
300 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
301 $locType = $defaultLocationType->id;
302 }
303
304 if ($field == 'country') {
305 $value = CRM_Core_PseudoConstant::countryIsoCode($value);
306 }
307 elseif ($field == 'state_province') {
308 $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
309 }
310
311 $isPrimary = 1;
312 if (isset($this->_params['onbehalf_location']['address'])
313 && count($this->_params['onbehalf_location']['address']) > 0) {
314 $isPrimary = 0;
315 }
316
317 $this->_params['onbehalf_location']['address'][$locType][$field] = $value;
318 if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
319 $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
320 }
321 $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
322 }
323 elseif (in_array($field, $blocks)) {
324 if (!$typeId || is_numeric($typeId)) {
325 $blockName = $fieldName = $field;
326 $locationType = 'location_type_id';
327 if ( $locType == 'Primary' ) {
328 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
329 $locationValue = $defaultLocationType->id;
330 }
331 else {
332 $locationValue = $locType;
333 }
334 $locTypeId = '';
335 $phoneExtField = array();
336
337 if ($field == 'url') {
338 $blockName = 'website';
339 $locationType = 'website_type_id';
340 list($field, $locationValue) = explode('-', $loc);
341 }
342 elseif ($field == 'im') {
343 $fieldName = 'name';
344 $locTypeId = 'provider_id';
345 $typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
346 }
347 elseif ($field == 'phone') {
348 list($field, $locType, $typeId) = explode('-', $loc);
349 $locTypeId = 'phone_type_id';
350
351 //check if extension field exists
352 $extField = str_replace('phone','phone_ext', $loc);
353 if (isset($this->_params['onbehalf'][$extField])) {
354 $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
355 }
356 }
357
358 $isPrimary = 1;
359 if ( isset ($this->_params['onbehalf_location'][$blockName] )
360 && count( $this->_params['onbehalf_location'][$blockName] ) > 0 ) {
361 $isPrimary = 0;
362 }
363 if ($locationValue) {
364 $blockValues = array(
365 $fieldName => $value,
366 $locationType => $locationValue,
367 'is_primary' => $isPrimary,
368 );
369
370 if ($locTypeId) {
371 $blockValues = array_merge($blockValues, array($locTypeId => $typeId));
372 }
373 if (!empty($phoneExtField)) {
374 $blockValues = array_merge($blockValues, $phoneExtField);
375 }
376
377 $this->_params['onbehalf_location'][$blockName][] = $blockValues;
378 }
379 }
380 }
381 elseif (strstr($loc, 'custom')) {
382 if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
383 $value = $this->_params['onbehalf']["{$loc}_id"];
384 }
385 $this->_params['onbehalf_location']["{$loc}"] = $value;
386 }
387 else {
388 if ($loc == 'contact_sub_type') {
389 $this->_params['onbehalf_location'][$loc] = $value;
390 }
391 else {
392 $this->_params['onbehalf_location'][$field] = $value;
393 }
394 }
395 }
396 }
397 elseif (!empty($this->_values['is_for_organization'])) {
398 // no on behalf of an organization, CRM-5519
399 // so reset loc blocks from main params.
400 foreach (array(
401 'phone', 'email', 'address') as $blk) {
402 if (isset($this->_params[$blk])) {
403 unset($this->_params[$blk]);
404 }
405 }
406 }
407
408 // if auto renew checkbox is set, initiate a open-ended recurring membership
409 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) &&
410 CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) {
411
412 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
413 // check if price set is not quick config
414 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
415 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
416 }
417 else {
418 // FIXME: set interval and unit based on selected membership type
419 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
420 $this->_params['selectMembership'], 'duration_interval'
421 );
422 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
423 $this->_params['selectMembership'], 'duration_unit'
424 );
425 }
426 }
427
428 if ($this->_pcpId) {
429 $params = $this->processPcp($this, $this->_params);
430 $this->_params = $params;
431 }
432 $this->_params['invoiceID'] = $this->get('invoiceID');
433
434 //carry campaign from profile.
435 if (array_key_exists('contribution_campaign_id', $this->_params)) {
436 $this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
437 }
438
439 // assign contribution page id to the template so we can add css class for it
440 $this->assign('contributionPageID', $this->_id);
441
442 $this->set('params', $this->_params);
443 }
444
445 /**
446 * Function to actually build the form
447 *
448 * @return void
449 * @access public
450 */
451 public function buildQuickForm() {
452 $this->assignToTemplate();
453
454 $params = $this->_params;
455 // make sure we have values for it
456 if ($this->_honor_block_is_active && !empty($params['soft_credit_type_id'])) {
457 $honorName = null;
458 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
459
460 $this->assign('honor_block_is_active', $this->_honor_block_is_active);
461 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
462 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']);
463
464 $fieldTypes = array('Contact');
465 $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']);
466 $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
467 }
468 $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
469 $amount_block_is_active = $this->get('amount_block_is_active');
470 $this->assign('amount_block_is_active', $amount_block_is_active);
471
472 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
473 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
474 if ($invoicing) {
475 $getTaxDetails = FALSE;
476 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
477 foreach ($this->_lineItem as $key => $value) {
478 foreach ($value as $v) {
479 if (isset($v['tax_rate'])) {
480 if ($v['tax_rate'] != '') {
481 $getTaxDetails = TRUE;
482 }
483 }
484 }
485 }
486 $this->assign('getTaxDetails', $getTaxDetails);
487 $this->assign('taxTerm', $taxTerm);
488 $this->assign('totalTaxAmount', $params['tax_amount']);
489 }
490 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
491 $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
492 $productID = $params['selectProduct'];
493 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
494 $productID, $option
495 );
496 $this->set('productID', $productID);
497 $this->set('option', $option);
498 }
499 $config = CRM_Core_Config::singleton();
500 if (in_array('CiviMember', $config->enableComponents)) {
501 if (isset($params['selectMembership']) &&
502 $params['selectMembership'] != 'no_thanks'
503 ) {
504 CRM_Member_BAO_Membership::buildMembershipBlock($this,
505 $this->_id,
506 $this->_membershipContactID,
507 FALSE,
508 $params['selectMembership'],
509 FALSE
510 );
511 }
512 else {
513 $this->assign('membershipBlock', FALSE);
514 }
515 }
516 $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
517 $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
518
519 if (!empty($params['hidden_onbehalf_profile'])) {
520 $ufJoinParams = array(
521 'module' => 'onBehalf',
522 'entity_table' => 'civicrm_contribution_page',
523 'entity_id' => $this->_id,
524 );
525 $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
526 $profileId = $OnBehalfProfile[0];
527
528 $fieldTypes = array('Contact', 'Organization');
529 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
530 $fieldTypes = array_merge($fieldTypes, $contactSubType);
531 if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
532 $fieldTypes = array_merge($fieldTypes, array('Membership'));
533 }
534 else {
535 $fieldTypes = array_merge($fieldTypes, array('Contribution'));
536 }
537
538 $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
539 }
540
541 $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
542 $this->assign('is_separate_payment', $this->_separateMembershipPayment);
543 if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
544 $this->assign('lineItem', $this->_lineItem);
545 } else {
546 $this->assign('is_quick_config', 1);
547 $this->_params['is_quick_config'] = 1;
548 }
549 $this->assign('priceSetID', $this->_priceSetId);
550 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name');
551 if ($this->_paymentProcessor &&
552 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType)
553 && !$this->_params['is_pay_later'] && !($this->_amount == 0)
554 ) {
555 $this->_checkoutButtonName = $this->getButtonName('next', 'checkout');
556 $this->add('image',
557 $this->_checkoutButtonName,
558 $this->_paymentProcessor['url_button'],
559 array('class' => 'crm-form-submit')
560 );
561
562 $this->addButtons(array(
563 array(
564 'type' => 'back',
565 'name' => ts('<< Go Back'),
566 ),
567 )
568 );
569 }
570 else {
571 if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] ||
572 $this->_amount <= 0.0 || $this->_params['is_pay_later'] ||
573 ($this->_separateMembershipPayment && $this->_amount <= 0.0)
574 ) {
575 $contribButton = ts('Continue >>');
576 $this->assign('button', ts('Continue'));
577 }
578 else {
579 $contribButton = ts('Make Contribution');
580 $this->assign('button', ts('Make Contribution'));
581 }
582 $this->addButtons(array(
583 array(
584 'type' => 'next',
585 'name' => $contribButton,
586 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
587 'isDefault' => TRUE,
588 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
589 ),
590 array(
591 'type' => 'back',
592 'name' => ts('Go Back'),
593 ),
594 )
595 );
596 }
597
598 $defaults = array();
599 $fields = array();
600 foreach ($this->_fields as $name => $dontCare) {
601 if ($name != 'onbehalf' || $name != 'honor') {
602 $fields[$name] = 1;
603 }
604 }
605 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
606
607 $contact = $this->_params;
608 foreach ($fields as $name => $dontCare) {
609 if (isset($contact[$name])) {
610 $defaults[$name] = $contact[$name];
611 if (substr($name, 0, 7) == 'custom_') {
612 $timeField = "{$name}_time";
613 if (isset($contact[$timeField])) {
614 $defaults[$timeField] = $contact[$timeField];
615 }
616 if (isset($contact["{$name}_id"])) {
617 $defaults["{$name}_id"] = $contact["{$name}_id"];
618 }
619 }
620 elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) {
621 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
622 }
623 }
624 }
625
626 $this->assign('useForMember', $this->get('useForMember'));
627
628 $this->setDefaults($defaults);
629
630 $this->freeze();
631 }
632
633 /**
634 * overwrite action, since we are only showing elements in frozen mode
635 * no help display needed
636 *
637 * @return int
638 * @access public
639 */
640 function getAction() {
641 if ($this->_action & CRM_Core_Action::PREVIEW) {
642 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
643 }
644 else {
645 return CRM_Core_Action::VIEW;
646 }
647 }
648
649 /**
650 * This function sets the default values for the form. Note that in edit/view mode
651 * the default values are retrieved from the database
652 *
653 * @access public
654 *
655 * @return void
656 */
657 function setDefaultValues() {}
658
659 /**
660 * Process the form
661 *
662 * @return void
663 * @access public
664 */
665 public function postProcess() {
666 $contactID = $this->getContactID();
667
668 // add a description field at the very beginning
669 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
670
671 // also add accounting code
672 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode',
673 $this->_values
674 );
675
676 // fix currency ID
677 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
678
679 //carry payment processor id.
680 if ($paymentProcessorId = CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
681 $this->_params['payment_processor_id'] = $paymentProcessorId;
682 }
683 if (!empty($params['image_URL'])) {
684 CRM_Contact_BAO_Contact::processImageParams($params);
685 }
686 $premiumParams = $membershipParams = $params = $this->_params;
687 $fields = array('email-Primary' => 1);
688
689 // get the add to groups
690 $addToGroups = array();
691
692 // now set the values for the billing location.
693 foreach ($this->_fields as $name => $value) {
694 $fields[$name] = 1;
695
696 // get the add to groups for uf fields
697 if (!empty($value['add_to_group_id'])) {
698 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
699 }
700 }
701
702 if (!array_key_exists('first_name', $fields)) {
703 $nameFields = array('first_name', 'middle_name', 'last_name');
704 foreach ($nameFields as $name) {
705 $fields[$name] = 1;
706 if (array_key_exists("billing_$name", $params)) {
707 $params[$name] = $params["billing_{$name}"];
708 $params['preserveDBName'] = TRUE;
709 }
710 }
711 }
712
713 // billing email address
714 $fields["email-{$this->_bltID}"] = 1;
715
716 //unset the billing parameters if it is pay later mode
717 //to avoid creation of billing location
718 if ($params['is_pay_later'] && !$this->_isBillingAddressRequiredForPayLater) {
719 $billingFields = array(
720 'billing_first_name',
721 'billing_middle_name',
722 'billing_last_name',
723 "billing_street_address-{$this->_bltID}",
724 "billing_city-{$this->_bltID}",
725 "billing_state_province-{$this->_bltID}",
726 "billing_state_province_id-{$this->_bltID}",
727 "billing_postal_code-{$this->_bltID}",
728 "billing_country-{$this->_bltID}",
729 "billing_country_id-{$this->_bltID}",
730 );
731
732 foreach ($billingFields as $value) {
733 unset($params[$value]);
734 unset($fields[$value]);
735 }
736 }
737
738 // if onbehalf-of-organization contribution, take out
739 // organization params in a separate variable, to make sure
740 // normal behavior is continued. And use that variable to
741 // process on-behalf-of functionality.
742 if (!empty($this->_params['hidden_onbehalf_profile'])) {
743 $behalfOrganization = array();
744 $orgFields = array('organization_name', 'organization_id', 'org_option');
745 foreach ($orgFields as $fld) {
746 if (array_key_exists($fld, $params)) {
747 $behalfOrganization[$fld] = $params[$fld];
748 unset($params[$fld]);
749 }
750 }
751
752 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
753 foreach ($params['onbehalf'] as $fld => $values) {
754 if (strstr($fld, 'custom_')) {
755 $behalfOrganization[$fld] = $values;
756 }
757 elseif (!(strstr($fld, '-'))) {
758 if (in_array($fld, array(
759 'contribution_campaign_id', 'member_campaign_id'))) {
760 $fld = 'campaign_id';
761 }
762 else {
763 $behalfOrganization[$fld] = $values;
764 }
765 $this->_params[$fld] = $values;
766 }
767 }
768 }
769
770 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
771 foreach ($params['onbehalf_location'] as $block => $vals) {
772 //fix for custom data (of type checkbox, multi-select)
773 if ( substr($block, 0, 7) == 'custom_' ) {
774 continue;
775 }
776 // fix the index of block elements
777 if (is_array($vals) ) {
778 foreach ( $vals as $key => $val ) {
779 //dont adjust the index of address block as
780 //it's index is WRT to location type
781 $newKey = ($block == 'address') ? $key : ++$key;
782 $behalfOrganization[$block][$newKey] = $val;
783 }
784 }
785 }
786 unset($params['onbehalf_location']);
787 }
788 if (!empty($params['onbehalf[image_URL]'])) {
789 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
790 }
791 }
792
793 // check for profile double opt-in and get groups to be subscribed
794 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
795
796 // since we are directly adding contact to group lets unset it from mailing
797 if (!empty($addToGroups)) {
798 foreach ($addToGroups as $groupId) {
799 if (isset($subscribeGroupIds[$groupId])) {
800 unset($subscribeGroupIds[$groupId]);
801 }
802 }
803 }
804
805 foreach ($addToGroups as $k) {
806 if (array_key_exists($k, $subscribeGroupIds)) {
807 unset($addToGroups[$k]);
808 }
809 }
810
811 if (empty($contactID)) {
812 $dupeParams = $params;
813 if (!empty($dupeParams['onbehalf'])) {
814 unset($dupeParams['onbehalf']);
815 }
816
817 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
818 $dedupeParams['check_permission'] = FALSE;
819 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
820
821 // if we find more than one contact, use the first one
822 $contactID = CRM_Utils_Array::value(0, $ids);
823
824 // Fetch default greeting id's if creating a contact
825 if (!$contactID) {
826 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
827 if (!isset($params[$greeting])) {
828 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
829 }
830 }
831 }
832 $contactType = NULL;
833 }
834 else {
835 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
836 }
837 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
838 $params,
839 $fields,
840 $contactID,
841 $addToGroups,
842 NULL,
843 $contactType,
844 TRUE
845 );
846
847 // Make the contact ID associated with the contribution available at the Class level.
848 // Also make available to the session.
849 //@todo consider handling this in $this->getContactID();
850 $this->set('contactID', $contactID);
851 $this->_contactID = $contactID;
852
853 //get email primary first if exist
854 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
855 if (!$subscriptionEmail['email']) {
856 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
857 }
858 // subscribing contact to groups
859 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
860 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
861 }
862
863 // If onbehalf-of-organization contribution / signup, add organization
864 // and it's location.
865 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
866 $ufFields = array();
867 foreach ($this->_fields['onbehalf'] as $name => $value) {
868 $ufFields[$name] = 1;
869 }
870 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
871 $this->_params, $ufFields
872 );
873 } else if (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
874 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
875 // store current user id as related contact for later use for mailing / activity..
876 $this->_values['related_contact'] = $contactID;
877 $this->_params['related_contact'] = $contactID;
878 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
879 $contactID = $this->_membershipContactID;
880 }
881
882 // lets store the contactID in the session
883 // for things like tell a friend
884 $session = CRM_Core_Session::singleton();
885 if (!$session->get('userID')) {
886 $session->set('transaction.userID', $contactID);
887 }
888 else {
889 $session->set('transaction.userID', NULL);
890 }
891
892 $this->_useForMember = $this->get('useForMember');
893
894 // store the fact that this is a membership and membership type is selected
895 $processMembership = FALSE;
896 if ((!empty($membershipParams['selectMembership']) &&
897 $membershipParams['selectMembership'] != 'no_thanks'
898 ) ||
899 $this->_useForMember
900 ) {
901 $processMembership = TRUE;
902
903 if (!$this->_useForMember) {
904 $this->assign('membership_assign', TRUE);
905 $this->set('membershipTypeID', $this->_params['selectMembership']);
906 }
907
908 if ($this->_action & CRM_Core_Action::PREVIEW) {
909 $membershipParams['is_test'] = 1;
910 }
911 if ($this->_params['is_pay_later']) {
912 $membershipParams['is_pay_later'] = 1;
913 }
914 }
915
916 if ($processMembership) {
917 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
918
919 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
920 if (isset($this->_params['related_contact'])) {
921 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
922 }
923 else {
924 $membershipParams['cms_contactID'] = $contactID;
925 }
926
927 //inherit campaign from contribution page.
928 if (!array_key_exists('campaign_id', $membershipParams)) {
929 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
930 }
931
932 if (!empty($membershipParams['onbehalf']) &&
933 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
934 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
935 }
936
937 $customFieldsFormatted = $fieldTypes = array();
938 if (!empty($membershipParams['onbehalf']) &&
939 is_array($membershipParams['onbehalf'])) {
940 foreach ($membershipParams['onbehalf'] as $key => $value) {
941 if (strstr($key, 'custom_')) {
942 $customFieldId = explode('_', $key);
943 CRM_Core_BAO_CustomField::formatCustomField(
944 $customFieldId[1],
945 $customFieldsFormatted,
946 $value,
947 'Membership',
948 NULL,
949 $contactID
950 );
951 }
952 }
953 $fieldTypes = array('Contact', 'Organization', 'Membership');
954 }
955
956 $priceFieldIds = $this->get('memberPriceFieldIDS');
957
958 if (!empty($priceFieldIds)) {
959 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
960 unset($priceFieldIds['id']);
961 $membershipTypeIds = array();
962 $membershipTypeTerms = array();
963 foreach ($priceFieldIds as $priceFieldId) {
964 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
965 $membershipTypeIds[] = $id;
966 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
967 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
968 $term = 1;
969 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
970 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
971 }
972 else {
973 $membershipTypeTerms[$id] = 1;
974 }
975 }
976 }
977 $membershipParams['selectMembership'] = $membershipTypeIds;
978 $membershipParams['financial_type_id'] = $contributionTypeID;
979 $membershipParams['types_terms'] = $membershipTypeTerms;
980 }
981 if (!empty($membershipParams['selectMembership'])) {
982 // CRM-12233
983 $membershipLineItems = array();
984 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
985 foreach ($this->_values['fee'] as $key => $feeValues) {
986 if ($feeValues['name'] == 'membership_amount') {
987 $fieldId = $this->_params['price_' . $key];
988 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
989 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
990 break;
991 }
992 }
993 }
994 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
995 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
996 // we need to explicitly create a CMS user in case of free memberships
997 // since it is done under processConfirm for paid memberships
998 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
999 $membershipParams['cms_contactID'],
1000 'email-' . $this->_bltID
1001 );
1002 }
1003 }
1004 }
1005 else {
1006 // at this point we've created a contact and stored its address etc
1007 // all the payment processors expect the name and address to be in the
1008 // so we copy stuff over to first_name etc.
1009 $paymentParams = $this->_params;
1010 $contributionTypeId = $this->_values['financial_type_id'];
1011
1012 $fieldTypes = array();
1013 if (!empty($paymentParams['onbehalf']) &&
1014 is_array($paymentParams['onbehalf'])
1015 ) {
1016 foreach ($paymentParams['onbehalf'] as $key => $value) {
1017 if (strstr($key, 'custom_')) {
1018 $this->_params[$key] = $value;
1019 }
1020 }
1021 $fieldTypes = array('Contact', 'Organization', 'Contribution');
1022 }
1023
1024 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
1025 $premiumParams, $contactID,
1026 $contributionTypeId,
1027 'contribution',
1028 $fieldTypes
1029 );
1030 }
1031 }
1032
1033 /**
1034 * Process the form
1035 *
1036 * @param $premiumParams
1037 * @param $contribution
1038 *
1039 * @return void
1040 * @access public
1041 */
1042 public function postProcessPremium($premiumParams, $contribution) {
1043 $hour = $minute = $second = 0;
1044 // assigning Premium information to receipt tpl
1045 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
1046 if ($selectProduct &&
1047 $selectProduct != 'no_thanks'
1048 ) {
1049 $startDate = $endDate = "";
1050 $this->assign('selectPremium', TRUE);
1051 $productDAO = new CRM_Contribute_DAO_Product();
1052 $productDAO->id = $selectProduct;
1053 $productDAO->find(TRUE);
1054 $this->assign('product_name', $productDAO->name);
1055 $this->assign('price', $productDAO->price);
1056 $this->assign('sku', $productDAO->sku);
1057 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1058
1059 $periodType = $productDAO->period_type;
1060
1061 if ($periodType) {
1062 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1063 $duration_unit = $productDAO->duration_unit;
1064 $duration_interval = $productDAO->duration_interval;
1065 if ($periodType == 'rolling') {
1066 $startDate = date('Y-m-d');
1067 }
1068 elseif ($periodType == 'fixed') {
1069 if ($fixed_period_start_day) {
1070 $date = explode('-', date('Y-m-d'));
1071 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1072 $day = substr($fixed_period_start_day, -2) . "<br>";
1073 $year = $date[0];
1074 $startDate = $year . '-' . $month . '-' . $day;
1075 }
1076 else {
1077 $startDate = date('Y-m-d');
1078 }
1079 }
1080
1081 $date = explode('-', $startDate);
1082 $year = $date[0];
1083 $month = $date[1];
1084 $day = $date[2];
1085
1086 switch ($duration_unit) {
1087 case 'year':
1088 $year = $year + $duration_interval;
1089 break;
1090
1091 case 'month':
1092 $month = $month + $duration_interval;
1093 break;
1094
1095 case 'day':
1096 $day = $day + $duration_interval;
1097 break;
1098
1099 case 'week':
1100 $day = $day + ($duration_interval * 7);
1101 }
1102 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1103 $this->assign('start_date', $startDate);
1104 $this->assign('end_date', $endDate);
1105 }
1106
1107 $dao = new CRM_Contribute_DAO_Premium();
1108 $dao->entity_table = 'civicrm_contribution_page';
1109 $dao->entity_id = $this->_id;
1110 $dao->find(TRUE);
1111 $this->assign('contact_phone', $dao->premiums_contact_phone);
1112 $this->assign('contact_email', $dao->premiums_contact_email);
1113
1114 //create Premium record
1115 $params = array(
1116 'product_id' => $premiumParams['selectProduct'],
1117 'contribution_id' => $contribution->id,
1118 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1119 'quantity' => 1,
1120 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1121 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1122 );
1123 if (!empty($premiumParams['selectProduct'])){
1124 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1125 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1126 $daoPremiumsProduct->premiums_id = $dao->id;
1127 $daoPremiumsProduct->find(true);
1128 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1129 }
1130 //Fixed For CRM-3901
1131 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1132 $daoContrProd->contribution_id = $contribution->id;
1133 if ($daoContrProd->find(TRUE)) {
1134 $params['id'] = $daoContrProd->id;
1135 }
1136
1137 CRM_Contribute_BAO_Contribution::addPremium($params);
1138 if ($productDAO->cost && !empty($params['financial_type_id'])) {
1139 $trxnParams = array(
1140 'cost' => $productDAO->cost,
1141 'currency' => $productDAO->currency,
1142 'financial_type_id' => $params['financial_type_id'],
1143 'contributionId' => $contribution->id
1144 );
1145 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1146 }
1147 }
1148 elseif ($selectProduct == 'no_thanks') {
1149 //Fixed For CRM-3901
1150 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1151 $daoContrProd->contribution_id = $contribution->id;
1152 if ($daoContrProd->find(TRUE)) {
1153 $daoContrProd->delete();
1154 }
1155 }
1156 }
1157
1158 /**
1159 * Process the contribution
1160 *
1161 * @param $form
1162 * @param array $params
1163 * @param array $result
1164 * @param integer $contactID
1165 * @param CRM_Financial_DAO_FinancialType $financialType
1166 * @param bool $pending
1167 * @param bool $online
1168 *
1169 * @param bool $isTest
1170 * @param array $lineItems
1171 *
1172 * @throws Exception
1173 * @return CRM_Contribute_DAO_Contribution
1174 * @access public
1175 */
1176 static function processContribution(
1177 &$form,
1178 $params,
1179 $result,
1180 $contactID,
1181 $financialType,
1182 $pending,
1183 $online,
1184 $isTest,
1185 $lineItems
1186 ) {
1187 $transaction = new CRM_Core_Transaction();
1188 $contribSoftContactId = $addressID = NULL;
1189
1190 // add these values for the recurringContrib function ,CRM-10188
1191 $params['financial_type_id'] = $financialType->id;
1192
1193 //create an contribution address
1194 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
1195 $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1196 }
1197
1198 //@todo - this is being set from the form to resolve CRM-10188 - an
1199 // eNotice caused by it not being set @ the front end
1200 // however, we then get it being over-written with null for backend contributions
1201 // a better fix would be to set the values in the respective forms rather than require
1202 // a function being shared by two forms to deal with their respective values
1203 // moving it to the BAO & not taking the $form as a param would make sense here.
1204 if(!isset($params['is_email_receipt'])){
1205 $params['is_email_receipt'] = CRM_Utils_Array::value( 'is_email_receipt', $form->_values );
1206 }
1207 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
1208
1209 // CRM-11885
1210 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1211 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1212 $nonDeductibleAmount = $params['non_deductible_amount'];
1213 }
1214 // if non_deductible_amount does NOT exist - then calculate it depending on:
1215 // $contributionType->is_deductible and whether there is a product (premium).
1216 else {
1217 //if ($contributionType->is_deductible && $deductibleMode) {
1218 if ($financialType->is_deductible) {
1219 if ($online && isset($params['selectProduct'])) {
1220 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1221 }
1222 if (!$online && isset($params['product_name'][0])) {
1223 $selectProduct = $params['product_name'][0];
1224 }
1225 // if there is a product - compare the value to the contribution amount
1226 if (isset($selectProduct) &&
1227 $selectProduct != 'no_thanks'
1228 ) {
1229 $productDAO = new CRM_Contribute_DAO_Product();
1230 $productDAO->id = $selectProduct;
1231 $productDAO->find(TRUE);
1232 // product value exceeds contribution amount
1233 if ($params['amount'] < $productDAO->price) {
1234 $nonDeductibleAmount = $params['amount'];
1235 }
1236 // product value does NOT exceed contribution amount
1237 else {
1238 $nonDeductibleAmount = $productDAO->price;
1239 }
1240 }
1241 // contribution is deductible - but there is no product
1242 else {
1243 $nonDeductibleAmount = '0.00';
1244 }
1245 }
1246 // contribution is NOT deductible
1247 else {
1248 $nonDeductibleAmount = $params['amount'];
1249 }
1250 }
1251
1252 $now = date('YmdHis');
1253 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
1254 if (!empty($form->_values['is_email_receipt'])) {
1255 $receiptDate = $now;
1256 }
1257
1258 //get the contrib page id.
1259 $contributionPageId = NULL;
1260 if ($online) {
1261 $contributionPageId = $form->_id;
1262 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1263 if (!array_key_exists('campaign_id', $params)) {
1264 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1265 }
1266 }
1267 else {
1268 //also for offline we do support - CRM-7290
1269 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1270 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1271 }
1272
1273 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1274 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
1275 // if its due to pcp
1276 if (!empty($params['pcp_made_through_id'])) {
1277 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
1278 'CRM_PCP_DAO_PCP',
1279 $params['pcp_made_through_id'],
1280 'contact_id'
1281 );
1282 }
1283 else {
1284 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1285 }
1286
1287 // Pass these details onto with the contribution to make them
1288 // available at hook_post_process, CRM-8908
1289 $params['soft_credit_to'] = $contribSoftContactId;
1290 }
1291
1292 if (isset($params['amount'])) {
1293 $contribParams = self::getContributionParams(
1294 $params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $form->_values['is_monetary'], $pending, $result, $receiptDate,
1295 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
1296 );
1297 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
1298
1299 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
1300 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1301 if ($invoicing) {
1302 $totalTaxAmount = 0;
1303 $dataArray = array();
1304 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1305 foreach ($lineItemValue as $key => $value) {
1306 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1307 if (isset($dataArray[$value['tax_rate']])) {
1308 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1309 }
1310 else {
1311 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1312 }
1313 }
1314 }
1315 }
1316 $smarty = CRM_Core_Smarty::singleton();
1317 $smarty->assign('dataArray', $dataArray);
1318 $smarty->assign('totalTaxAmount', $params['tax_amount']);
1319 }
1320 if (is_a($contribution, 'CRM_Core_Error')) {
1321 $message = CRM_Core_Error::getMessages($contribution);
1322 CRM_Core_Error::fatal($message);
1323 }
1324
1325 // lets store it in the form variable so postProcess hook can get to this and use it
1326 $form->_contributionID = $contribution->id;
1327 }
1328
1329 //CRM-13981, processing honor contact into soft-credit contribution
1330 CRM_Contact_Form_ProfileContact::postProcess($form);
1331
1332 // process soft credit / pcp pages
1333 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1334
1335 //handle pledge stuff.
1336 if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) &&
1337 (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))
1338 ) {
1339
1340 if (!empty($form->_values['pledge_id'])) {
1341
1342 //when user doing pledge payments.
1343 //update the schedule when payment(s) are made
1344 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1345 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1346 'CRM_Pledge_DAO_PledgePayment',
1347 $paymentId,
1348 'scheduled_amount',
1349 'id'
1350 );
1351
1352 $pledgePaymentParams = array(
1353 'id' => $paymentId,
1354 'contribution_id' => $contribution->id,
1355 'status_id' => $contribution->contribution_status_id,
1356 'actual_amount' => $scheduledAmount,
1357 );
1358
1359
1360 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1361 }
1362
1363 //update pledge status according to the new payment statuses
1364 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1365 }
1366 else {
1367 //when user creating pledge record.
1368 $pledgeParams = array();
1369 $pledgeParams['contact_id'] = $contribution->contact_id;
1370 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1371 $pledgeParams['contribution_id'] = $contribution->id;
1372 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1373 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1374 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1375 $pledgeParams['installments'] = $params['pledge_installments'];
1376 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1377 if ($pledgeParams['frequency_unit'] == 'month') {
1378 $pledgeParams['frequency_day'] = intval(date("d"));
1379 }
1380 else {
1381 $pledgeParams['frequency_day'] = 1;
1382 }
1383 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1384 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1385 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1386 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1387 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1388 $pledgeParams['is_test'] = $contribution->is_test;
1389 $pledgeParams['acknowledge_date'] = date('Ymd');
1390 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1391
1392 //inherit campaign from contirb page.
1393 $pledgeParams['campaign_id'] = $campaignId;
1394
1395 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1396
1397 $form->_params['pledge_id'] = $pledge->id;
1398
1399 //send acknowledgment email. only when pledge is created
1400 if ($pledge->id) {
1401 //build params to send acknowledgment.
1402 $pledgeParams['id'] = $pledge->id;
1403 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1404 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1405
1406 //scheduled amount will be same as installment_amount.
1407 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1408
1409 //get total pledge amount.
1410 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1411
1412 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1413 }
1414 }
1415 }
1416
1417 if ($online && $contribution) {
1418 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1419 CRM_Core_DAO::$_nullArray,
1420 'civicrm_contribution',
1421 $contribution->id,
1422 'Contribution'
1423 );
1424 }
1425 elseif ($contribution) {
1426 //handle custom data.
1427 $params['contribution_id'] = $contribution->id;
1428 if (!empty($params['custom']) &&
1429 is_array($params['custom']) &&
1430 !is_a($contribution, 'CRM_Core_Error')
1431 ) {
1432 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1433 }
1434 }
1435 // Save note
1436 if ($contribution && !empty($params['contribution_note'])) {
1437 $noteParams = array(
1438 'entity_table' => 'civicrm_contribution',
1439 'note' => $params['contribution_note'],
1440 'entity_id' => $contribution->id,
1441 'contact_id' => $contribution->contact_id,
1442 'modified_date' => date('Ymd'),
1443 );
1444
1445 CRM_Core_BAO_Note::add($noteParams, array());
1446 }
1447
1448
1449 if (isset($params['related_contact'])) {
1450 $contactID = $params['related_contact'];
1451 }
1452 elseif (isset($params['cms_contactID'])) {
1453 $contactID = $params['cms_contactID'];
1454 }
1455
1456 //create contribution activity w/ individual and target
1457 //activity w/ organisation contact id when onbelf, CRM-4027
1458 $targetContactID = NULL;
1459 if (!empty($params['hidden_onbehalf_profile'])) {
1460 $targetContactID = $contribution->contact_id;
1461 $contribution->contact_id = $contactID;
1462 }
1463
1464 // create an activity record
1465 if ($contribution) {
1466 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1467 }
1468
1469 $transaction->commit();
1470 // CRM-13074 - create the CMSUser after the transaction is completed as it
1471 // is not appropriate to delete a valid contribution if a user create problem occurs
1472 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1473 $contactID,
1474 'email-' . $form->_bltID
1475 );
1476 return $contribution;
1477 }
1478
1479 /**
1480 * Create the recurring contribution record
1481 *
1482 */
1483 static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1484 // return if this page is not set for recurring
1485 // or the user has not chosen the recurring option
1486
1487 //this is online case validation.
1488 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
1489 return NULL;
1490 }
1491
1492 $recurParams = array('contact_id' => $contactID);
1493 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1494 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1495 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1496 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1497 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1498 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1499
1500 // CRM-14354: For an auto-renewing membership with an additional contribution,
1501 // if separate payments is not enabled, make sure only the membership fee recurs
1502 if ($form->_membershipBlock['is_separate_payment'] === '0'
1503 && isset($params['selectMembership'])
1504 && $form->_values['is_allow_other_amount'] == '1'
1505 ) {
1506 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1507 }
1508
1509 $recurParams['is_test'] = 0;
1510 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1511 (isset($form->_mode) && ($form->_mode == 'test'))
1512 ) {
1513 $recurParams['is_test'] = 1;
1514 }
1515
1516 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1517 if (!empty($params['receive_date'])) {
1518 $recurParams['start_date'] = $params['receive_date'];
1519 }
1520 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1521 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1522 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1523 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1524 // we need to add a unique trxn_id to avoid a unique key error
1525 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1526 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1527 $recurParams['financial_type_id'] = $contributionType->id;
1528
1529 if (!$online || $form->_values['is_monetary']) {
1530 $recurParams['payment_instrument_id'] = 1;
1531 }
1532
1533 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1534 if ($online) {
1535 if (!array_key_exists('campaign_id', $params)) {
1536 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1537 }
1538 }
1539 $recurParams['campaign_id'] = $campaignId;
1540
1541 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1542 if (is_a($recurring, 'CRM_Core_Error')) {
1543 CRM_Core_Error::displaySessionError($recurring);
1544 $urlString = 'civicrm/contribute/transact';
1545 $urlParams = '_qf_Main_display=true';
1546 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1547 $urlString = 'civicrm/contact/view/contribution';
1548 $urlParams = "action=add&cid={$form->_contactID}";
1549 if ($form->_mode) {
1550 $urlParams .= "&mode={$form->_mode}";
1551 }
1552 }
1553 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1554 }
1555
1556 return $recurring->id;
1557 }
1558
1559 /**
1560 * Function to add on behalf of organization and it's location
1561 *
1562 * @param $behalfOrganization array array of organization info
1563 * @param $contactID int individual contact id. One
1564 * who is doing the process of signup / contribution.
1565 *
1566 * @param $values array form values array
1567 * @param $params
1568 * @param null $fields
1569 *
1570 * @return void
1571 * @access public
1572 */
1573 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1574 $isCurrentEmployer = FALSE;
1575 $dupeIDs = array();
1576 $orgID = NULL;
1577 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1578 $orgID = $behalfOrganization['organization_id'];
1579 unset($behalfOrganization['organization_id']);
1580 $isCurrentEmployer = TRUE;
1581 }
1582
1583 // formalities for creating / editing organization.
1584 $behalfOrganization['contact_type'] = 'Organization';
1585
1586 // get the relationship type id
1587 $relType = new CRM_Contact_DAO_RelationshipType();
1588 $relType->name_a_b = 'Employee of';
1589 $relType->find(TRUE);
1590 $relTypeId = $relType->id;
1591
1592 // keep relationship params ready
1593 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1594 $relParams['is_permission_a_b'] = 1;
1595 $relParams['is_active'] = 1;
1596
1597 if (!$orgID) {
1598 // check if matching organization contact exists
1599 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1600 $dedupeParams['check_permission'] = FALSE;
1601 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1602
1603 // CRM-6243 says to pick the first org even if more than one match
1604 if (count($dupeIDs) >= 1) {
1605 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1606 // don't allow name edit
1607 unset($behalfOrganization['organization_name']);
1608 }
1609 }
1610 else {
1611 // if found permissioned related organization, allow location edit
1612 $behalfOrganization['contact_id'] = $orgID;
1613 // don't allow name edit
1614 unset($behalfOrganization['organization_name']);
1615 }
1616
1617 // handling for image url
1618 if (!empty($behalfOrganization['image_URL'])) {
1619 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1620 }
1621
1622 // create organization, add location
1623 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1624 NULL, NULL, 'Organization'
1625 );
1626 // create relationship
1627 $relParams['contact_check'][$orgID] = 1;
1628 $cid = array('contact' => $contactID);
1629 CRM_Contact_BAO_Relationship::create($relParams, $cid);
1630
1631 // if multiple match - send a duplicate alert
1632 if ($dupeIDs && (count($dupeIDs) > 1)) {
1633 $values['onbehalf_dupe_alert'] = 1;
1634 // required for IPN
1635 $params['onbehalf_dupe_alert'] = 1;
1636 }
1637
1638 // make sure organization-contact-id is considered for recording
1639 // contribution/membership etc..
1640 if ($contactID != $orgID) {
1641 // take a note of contact-id, so we can send the
1642 // receipt to individual contact as well.
1643
1644 // required for mailing/template display ..etc
1645 $values['related_contact'] = $contactID;
1646 // required for IPN
1647 $params['related_contact'] = $contactID;
1648
1649 //make this employee of relationship as current
1650 //employer / employee relationship, CRM-3532
1651 if ($isCurrentEmployer &&
1652 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1653 ) {
1654 $isCurrentEmployer = FALSE;
1655 }
1656
1657 if (!$isCurrentEmployer && $orgID) {
1658 //build current employer params
1659 $currentEmpParams[$contactID] = $orgID;
1660 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1661 }
1662
1663 // contribution / signup will be done using this
1664 // organization id.
1665 $contactID = $orgID;
1666 }
1667 }
1668
1669 /**
1670 * Function used to save pcp / soft credit entry
1671 * This is used by contribution and also event pcps
1672 *
1673 * @param array $params associated array
1674 * @param object $contribution contribution object
1675 *
1676 * @static
1677 * @access public
1678 */
1679 static function processPcpSoft(&$params, &$contribution) {
1680 //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1681 if (!empty($params['soft_credit_to'])) {
1682 $contributionSoftParams = array();
1683 foreach (array(
1684 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) {
1685 if (!empty($params[$val])) {
1686 $contributionSoftParams[$val] = $params[$val];
1687 }
1688 }
1689
1690 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1691 // add contribution id
1692 $contributionSoftParams['contribution_id'] = $contribution->id;
1693 // add pcp id
1694 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1695
1696 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
1697
1698 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
1699 }
1700 }
1701
1702 /**
1703 * Function used to se pcp related defaults / params
1704 * This is used by contribution and also event pcps
1705 *
1706 * @param object $page form object
1707 * @param array $params associated array
1708 *
1709 * @return array
1710 * @static
1711 * @access public
1712 */
1713 static function processPcp(&$page, $params) {
1714 $params['pcp_made_through_id'] = $page->_pcpId;
1715 $page->assign('pcpBlock', TRUE);
1716 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1717 $params['pcp_roll_nickname'] = ts('Anonymous');
1718 $params['pcp_is_anonymous'] = 1;
1719 }
1720 else {
1721 $params['pcp_is_anonymous'] = 0;
1722 }
1723 foreach (array(
1724 'pcp_display_in_roll',
1725 'pcp_is_anonymous',
1726 'pcp_roll_nickname',
1727 'pcp_personal_note'
1728 ) as $val) {
1729 if (!empty($params[$val])) {
1730 $page->assign($val, $params[$val]);
1731 }
1732 }
1733
1734 return $params;
1735 }
1736
1737 /**
1738 * @param array $membershipParams
1739 * @param integer $contactID
1740 * @param array $customFieldsFormatted
1741 * @param array $fieldTypes
1742 * @param array $premiumParams
1743 * @param array $membershipLineItems line items specifically relating to memberships
1744 */
1745 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems) {
1746 try {
1747 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1748 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1749 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1750 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1751
1752 $isPaidMembership = FALSE;
1753 if($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1754 //amount must be greater than zero for
1755 //adding contribution record to contribution table.
1756 //this condition arises when separate membership payment is
1757 //enabled and contribution amount is not selected. fix for CRM-3010
1758 $isPaidMembership = TRUE;
1759 }
1760 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
1761
1762 if ($this->_values['amount_block_is_active']) {
1763 $contributionTypeId = $this->_values['financial_type_id'];
1764 }
1765 else {
1766 $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id' ,$membershipParams));
1767 }
1768
1769 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
1770 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $contributionTypeId,
1771 $membershipLineItems
1772 );
1773 $this->assign('membership_assign', TRUE);
1774 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1775 }
1776 catch (CRM_Core_Exception $e) {
1777 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1778 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1779 }
1780 }
1781
1782 /**
1783 * Are we going to do 2 financial transactions?
1784 * ie the membership block supports a separate transactions AND the contribution form has been configured for a contribution
1785 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1786 *
1787 *
1788 * @param integer $formID
1789 * @param bool $amountBlockActiveOnForm
1790 *
1791 * @return bool
1792 */
1793 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1794 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1795 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1796 return TRUE;
1797 }
1798 return FALSE;
1799 }
1800
1801 /**
1802 * This function sets the fields
1803 * - $this->_params['amount_level']
1804 * - $this->_params['selectMembership']
1805 * And under certain circumstances sets
1806 * $this->_params['amount'] = null;
1807 *
1808 * @param $priceSetID
1809 *
1810 * @internal param $isQuickConfig
1811 * @internal param $priceField
1812 */
1813 public function setFormAmountFields($priceSetID) {
1814 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1815 $priceField = new CRM_Price_DAO_PriceField();
1816 $priceField->price_set_id = $priceSetID;
1817 $priceField->orderBy('weight');
1818 $priceField->find();
1819 $paramWeDoNotUnderstand = NULL;
1820
1821 while ($priceField->fetch()) {
1822 if ($priceField->name == "contribution_amount") {
1823 $paramWeDoNotUnderstand = $priceField->id;
1824 }
1825 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1826 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
1827 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1828 $this->_params["price_{$priceField->id}"], 'label');
1829 }
1830 if ($priceField->name == "membership_amount") {
1831 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1832 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1833 }
1834 } // if separate payment we set contribution amount to be null, so that it will not show contribution amount same as membership amount.
1835 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1836 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1837 // so we should merge them together
1838 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1839 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1840 elseif (
1841 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1842 && !empty($this->_values['fee'][$priceField->id])
1843 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1844 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1845 && empty($this->_params["price_{$priceField->id}"])
1846 ) {
1847 $this->_params['amount'] = null;
1848 }
1849
1850 // Fix for CRM-14375 - If we are using separate payments and "no
1851 // thank you" is selected for the additional contribution, set
1852 // contribution amount to be null, so that it will not show
1853 // contribution amount same as membership amount.
1854 //@todo - merge with section above
1855 if ($this->_membershipBlock['is_separate_payment']
1856 && !empty($this->_values['fee'][$priceField->id])
1857 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1858 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1859 ) {
1860 $this->_params['amount'] = null;
1861 }
1862 }
1863 }
1864
1865 static function submit($params) {
1866 $form = new CRM_Contribute_Form_Contribution_Confirm();
1867 $form->_id = $params['id'];
1868 if (!empty($params['contact_id'])) {
1869 $form->_contactID = $params['contact_id'];
1870 }
1871 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1872 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
1873 //this way the mocked up controller ignores the session stuff
1874 $_SERVER['REQUEST_METHOD'] = 'GET';
1875 $form->controller = new CRM_Contribute_Controller_Contribution();
1876 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1877 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
1878 $form->_amount = $params['amount'];
1879 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1880 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
1881 $priceSetFields = reset($priceFields);
1882 $form->_values['fee'] = $priceSetFields['fields'];
1883 $form->_priceSetId = $priceSetID;
1884 $form->setFormAmountFields($priceSetID);
1885 if (!empty($params['payment_processor'])) {
1886 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array('id' => $params['payment_processor']));
1887 if ($form->_paymentProcessor['billing_mode'] ==1) {
1888 $form->_contributeMode = 'direct';
1889 }
1890 else {
1891 $form->_contributeMode = 'notify';
1892 }
1893 }
1894 $priceFields = $priceFields[$priceSetID]['fields'];
1895 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1896 $form->_lineItem = array($priceSetID => $lineItems);
1897 $form->postProcess();
1898 }
1899
1900 /**
1901 * Helper function for static submit function - set relevant params - help us to build up an array that we can pass in
1902 * @param $id
1903 * @param array $params
1904 *
1905 * @return array
1906 * @throws CiviCRM_API3_Exception
1907 */
1908 static function getFormParams($id, array $params) {
1909 if(!isset($params['is_pay_later'])) {
1910 if (!empty($params['payment_processor'])) {
1911 $params['is_pay_later'] = 0;
1912 }
1913 else {
1914 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1915 'id' => $id,
1916 'return' => 'is_pay_later'
1917 ));
1918 }
1919 }
1920 if(empty($params['price_set_id'])) {
1921 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
1922 }
1923 return $params;
1924 }
1925 }