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