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