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