Merge branch 'CRM-15474' of github.com:colemanw/civicrm-core into CRM-15527
[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 if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array('Multi-Select','AdvMulti-Select'))) {
590 foreach ($fieldValue as $key => $value) {
591 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
592 }
593 }
594 else {
595 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
596 }
597 }
598 }
599 elseif (isset($contact[$name])) {
600 $defaults[$name] = $contact[$name];
601 if (substr($name, 0, 7) == 'custom_') {
602 $timeField = "{$name}_time";
603 if (isset($contact[$timeField])) {
604 $defaults[$timeField] = $contact[$timeField];
605 }
606 if (isset($contact["{$name}_id"])) {
607 $defaults["{$name}_id"] = $contact["{$name}_id"];
608 }
609 }
610 elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) {
611 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
612 }
613 }
614 }
615
616 $this->assign('useForMember', $this->get('useForMember'));
617
618 $this->setDefaults($defaults);
619
620 $this->freeze();
621 }
622
623 /**
624 * overwrite action, since we are only showing elements in frozen mode
625 * no help display needed
626 *
627 * @return int
628 * @access public
629 */
630 function getAction() {
631 if ($this->_action & CRM_Core_Action::PREVIEW) {
632 return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
633 }
634 else {
635 return CRM_Core_Action::VIEW;
636 }
637 }
638
639 /**
640 * This function sets the default values for the form. Note that in edit/view mode
641 * the default values are retrieved from the database
642 *
643 * @access public
644 *
645 * @return void
646 */
647 function setDefaultValues() {}
648
649 /**
650 * Process the form
651 *
652 * @return void
653 * @access public
654 */
655 public function postProcess() {
656 $contactID = $this->getContactID();
657
658 // add a description field at the very beginning
659 $this->_params['description'] = ts('Online Contribution') . ': ' . (($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
660
661 // also add accounting code
662 $this->_params['accountingCode'] = CRM_Utils_Array::value('accountingCode',
663 $this->_values
664 );
665
666 // fix currency ID
667 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
668
669 //carry payment processor id.
670 if ($paymentProcessorId = CRM_Utils_Array::value('id', $this->_paymentProcessor)) {
671 $this->_params['payment_processor_id'] = $paymentProcessorId;
672 }
673 if (!empty($params['image_URL'])) {
674 CRM_Contact_BAO_Contact::processImageParams($params);
675 }
676 $premiumParams = $membershipParams = $params = $this->_params;
677 $fields = array('email-Primary' => 1);
678
679 // get the add to groups
680 $addToGroups = array();
681
682 // now set the values for the billing location.
683 foreach ($this->_fields as $name => $value) {
684 $fields[$name] = 1;
685
686 // get the add to groups for uf fields
687 if (!empty($value['add_to_group_id'])) {
688 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
689 }
690 }
691
692 if (!array_key_exists('first_name', $fields)) {
693 $nameFields = array('first_name', 'middle_name', 'last_name');
694 foreach ($nameFields as $name) {
695 $fields[$name] = 1;
696 if (array_key_exists("billing_$name", $params)) {
697 $params[$name] = $params["billing_{$name}"];
698 $params['preserveDBName'] = TRUE;
699 }
700 }
701 }
702
703 // billing email address
704 $fields["email-{$this->_bltID}"] = 1;
705
706 //unset the billing parameters if it is pay later mode
707 //to avoid creation of billing location
708 if ($params['is_pay_later']) {
709 $billingFields = array(
710 'billing_first_name',
711 'billing_middle_name',
712 'billing_last_name',
713 "billing_street_address-{$this->_bltID}",
714 "billing_city-{$this->_bltID}",
715 "billing_state_province-{$this->_bltID}",
716 "billing_state_province_id-{$this->_bltID}",
717 "billing_postal_code-{$this->_bltID}",
718 "billing_country-{$this->_bltID}",
719 "billing_country_id-{$this->_bltID}",
720 );
721
722 foreach ($billingFields as $value) {
723 unset($params[$value]);
724 unset($fields[$value]);
725 }
726 }
727
728 // if onbehalf-of-organization contribution, take out
729 // organization params in a separate variable, to make sure
730 // normal behavior is continued. And use that variable to
731 // process on-behalf-of functionality.
732 if (!empty($this->_params['hidden_onbehalf_profile'])) {
733 $behalfOrganization = array();
734 $orgFields = array('organization_name', 'organization_id', 'org_option');
735 foreach ($orgFields as $fld) {
736 if (array_key_exists($fld, $params)) {
737 $behalfOrganization[$fld] = $params[$fld];
738 unset($params[$fld]);
739 }
740 }
741
742 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
743 foreach ($params['onbehalf'] as $fld => $values) {
744 if (strstr($fld, 'custom_')) {
745 $behalfOrganization[$fld] = $values;
746 }
747 elseif (!(strstr($fld, '-'))) {
748 if (in_array($fld, array(
749 'contribution_campaign_id', 'member_campaign_id'))) {
750 $fld = 'campaign_id';
751 }
752 else {
753 $behalfOrganization[$fld] = $values;
754 }
755 $this->_params[$fld] = $values;
756 }
757 }
758 }
759
760 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
761 foreach ($params['onbehalf_location'] as $block => $vals) {
762 //fix for custom data (of type checkbox, multi-select)
763 if ( substr($block, 0, 7) == 'custom_' ) {
764 continue;
765 }
766 // fix the index of block elements
767 if (is_array($vals) ) {
768 foreach ( $vals as $key => $val ) {
769 //dont adjust the index of address block as
770 //it's index is WRT to location type
771 $newKey = ($block == 'address') ? $key : ++$key;
772 $behalfOrganization[$block][$newKey] = $val;
773 }
774 }
775 }
776 unset($params['onbehalf_location']);
777 }
778 if (!empty($params['onbehalf[image_URL]'])) {
779 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
780 }
781 }
782
783 // check for profile double opt-in and get groups to be subscribed
784 $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID);
785
786 // since we are directly adding contact to group lets unset it from mailing
787 if (!empty($addToGroups)) {
788 foreach ($addToGroups as $groupId) {
789 if (isset($subscribeGroupIds[$groupId])) {
790 unset($subscribeGroupIds[$groupId]);
791 }
792 }
793 }
794
795 foreach ($addToGroups as $k) {
796 if (array_key_exists($k, $subscribeGroupIds)) {
797 unset($addToGroups[$k]);
798 }
799 }
800
801 if (empty($contactID)) {
802 $dupeParams = $params;
803 if (!empty($dupeParams['onbehalf'])) {
804 unset($dupeParams['onbehalf']);
805 }
806
807 $dedupeParams = CRM_Dedupe_Finder::formatParams($dupeParams, 'Individual');
808 $dedupeParams['check_permission'] = FALSE;
809 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
810
811 // if we find more than one contact, use the first one
812 $contactID = CRM_Utils_Array::value(0, $ids);
813
814 // Fetch default greeting id's if creating a contact
815 if (!$contactID) {
816 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
817 if (!isset($params[$greeting])) {
818 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting);
819 }
820 }
821 }
822 $contactType = NULL;
823 }
824 else {
825 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
826 }
827 $contactID = CRM_Contact_BAO_Contact::createProfileContact(
828 $params,
829 $fields,
830 $contactID,
831 $addToGroups,
832 NULL,
833 $contactType,
834 TRUE
835 );
836
837 // Make the contact ID associated with the contribution available at the Class level.
838 // Also make available to the session.
839 //@todo consider handling this in $this->getContactID();
840 $this->set('contactID', $contactID);
841 $this->_contactID = $contactID;
842
843 //get email primary first if exist
844 $subscriptionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
845 if (!$subscriptionEmail['email']) {
846 $subscriptionEmail['email'] = CRM_Utils_Array::value("email-{$this->_bltID}", $params);
847 }
848 // subscribing contact to groups
849 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
850 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
851 }
852
853 // If onbehalf-of-organization contribution / signup, add organization
854 // and it's location.
855 if (isset($params['hidden_onbehalf_profile']) && isset($behalfOrganization['organization_name'])) {
856 $ufFields = array();
857 foreach ($this->_fields['onbehalf'] as $name => $value) {
858 $ufFields[$name] = 1;
859 }
860 self::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values,
861 $this->_params, $ufFields
862 );
863 } else if (!empty($this->_membershipContactID) && $contactID != $this->_membershipContactID) {
864 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
865 // store current user id as related contact for later use for mailing / activity..
866 $this->_values['related_contact'] = $contactID;
867 $this->_params['related_contact'] = $contactID;
868 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
869 $contactID = $this->_membershipContactID;
870 }
871
872 // lets store the contactID in the session
873 // for things like tell a friend
874 $session = CRM_Core_Session::singleton();
875 if (!$session->get('userID')) {
876 $session->set('transaction.userID', $contactID);
877 }
878 else {
879 $session->set('transaction.userID', NULL);
880 }
881
882 $this->_useForMember = $this->get('useForMember');
883
884 // store the fact that this is a membership and membership type is selected
885 $processMembership = FALSE;
886 if ((!empty($membershipParams['selectMembership']) &&
887 $membershipParams['selectMembership'] != 'no_thanks'
888 ) ||
889 $this->_useForMember
890 ) {
891 $processMembership = TRUE;
892
893 if (!$this->_useForMember) {
894 $this->assign('membership_assign', TRUE);
895 $this->set('membershipTypeID', $this->_params['selectMembership']);
896 }
897
898 if ($this->_action & CRM_Core_Action::PREVIEW) {
899 $membershipParams['is_test'] = 1;
900 }
901 if ($this->_params['is_pay_later']) {
902 $membershipParams['is_pay_later'] = 1;
903 }
904 }
905
906 if ($processMembership) {
907 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $membershipParams, TRUE);
908
909 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
910 if (isset($this->_params['related_contact'])) {
911 $membershipParams['cms_contactID'] = $this->_params['related_contact'];
912 }
913 else {
914 $membershipParams['cms_contactID'] = $contactID;
915 }
916
917 //inherit campaign from contribution page.
918 if (!array_key_exists('campaign_id', $membershipParams)) {
919 $membershipParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
920 }
921
922 if (!empty($membershipParams['onbehalf']) &&
923 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
924 $this->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
925 }
926
927 $customFieldsFormatted = $fieldTypes = array();
928 if (!empty($membershipParams['onbehalf']) &&
929 is_array($membershipParams['onbehalf'])) {
930 foreach ($membershipParams['onbehalf'] as $key => $value) {
931 if (strstr($key, 'custom_')) {
932 $customFieldId = explode('_', $key);
933 CRM_Core_BAO_CustomField::formatCustomField(
934 $customFieldId[1],
935 $customFieldsFormatted,
936 $value,
937 'Membership',
938 NULL,
939 $contactID
940 );
941 }
942 }
943 $fieldTypes = array('Contact', 'Organization', 'Membership');
944 }
945
946 $priceFieldIds = $this->get('memberPriceFieldIDS');
947
948 if (!empty($priceFieldIds)) {
949 $contributionTypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
950 unset($priceFieldIds['id']);
951 $membershipTypeIds = array();
952 $membershipTypeTerms = array();
953 foreach ($priceFieldIds as $priceFieldId) {
954 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
955 $membershipTypeIds[] = $id;
956 //@todo the value for $term is immediately overwritten. It is unclear from the code whether it was intentional to
957 // do this or a double = was intended (this ambiguity is the reason many IDEs complain about 'assignment in condition'
958 $term = 1;
959 if ($term = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms')) {
960 $membershipTypeTerms[$id] = ($term > 1) ? $term : 1;
961 }
962 else {
963 $membershipTypeTerms[$id] = 1;
964 }
965 }
966 }
967 $membershipParams['selectMembership'] = $membershipTypeIds;
968 $membershipParams['financial_type_id'] = $contributionTypeID;
969 $membershipParams['types_terms'] = $membershipTypeTerms;
970 }
971 if (!empty($membershipParams['selectMembership'])) {
972 // CRM-12233
973 $membershipLineItems = array();
974 if ($this->_separateMembershipPayment && $this->_values['amount_block_is_active']) {
975 foreach ($this->_values['fee'] as $key => $feeValues) {
976 if ($feeValues['name'] == 'membership_amount') {
977 $fieldId = $this->_params['price_' . $key];
978 $membershipLineItems[$this->_priceSetId][$fieldId] = $this->_lineItem[$this->_priceSetId][$fieldId];
979 unset($this->_lineItem[$this->_priceSetId][$fieldId]);
980 break;
981 }
982 }
983 }
984 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
985 if (!$this->_amount > 0.0 || !$membershipParams['amount']) {
986 // we need to explicitly create a CMS user in case of free memberships
987 // since it is done under processConfirm for paid memberships
988 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams,
989 $membershipParams['cms_contactID'],
990 'email-' . $this->_bltID
991 );
992 }
993 }
994 }
995 else {
996 // at this point we've created a contact and stored its address etc
997 // all the payment processors expect the name and address to be in the
998 // so we copy stuff over to first_name etc.
999 $paymentParams = $this->_params;
1000 $contributionTypeId = $this->_values['financial_type_id'];
1001
1002 $fieldTypes = array();
1003 if (!empty($paymentParams['onbehalf']) &&
1004 is_array($paymentParams['onbehalf'])
1005 ) {
1006 foreach ($paymentParams['onbehalf'] as $key => $value) {
1007 if (strstr($key, 'custom_')) {
1008 $this->_params[$key] = $value;
1009 }
1010 }
1011 $fieldTypes = array('Contact', 'Organization', 'Contribution');
1012 }
1013
1014 CRM_Contribute_BAO_Contribution_Utils::processConfirm($this, $paymentParams,
1015 $premiumParams, $contactID,
1016 $contributionTypeId,
1017 'contribution',
1018 $fieldTypes
1019 );
1020 }
1021 }
1022
1023 /**
1024 * Process the form
1025 *
1026 * @param $premiumParams
1027 * @param $contribution
1028 *
1029 * @return void
1030 * @access public
1031 */
1032 public function postProcessPremium($premiumParams, $contribution) {
1033 $hour = $minute = $second = 0;
1034 // assigning Premium information to receipt tpl
1035 $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
1036 if ($selectProduct &&
1037 $selectProduct != 'no_thanks'
1038 ) {
1039 $startDate = $endDate = "";
1040 $this->assign('selectPremium', TRUE);
1041 $productDAO = new CRM_Contribute_DAO_Product();
1042 $productDAO->id = $selectProduct;
1043 $productDAO->find(TRUE);
1044 $this->assign('product_name', $productDAO->name);
1045 $this->assign('price', $productDAO->price);
1046 $this->assign('sku', $productDAO->sku);
1047 $this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
1048
1049 $periodType = $productDAO->period_type;
1050
1051 if ($periodType) {
1052 $fixed_period_start_day = $productDAO->fixed_period_start_day;
1053 $duration_unit = $productDAO->duration_unit;
1054 $duration_interval = $productDAO->duration_interval;
1055 if ($periodType == 'rolling') {
1056 $startDate = date('Y-m-d');
1057 }
1058 elseif ($periodType == 'fixed') {
1059 if ($fixed_period_start_day) {
1060 $date = explode('-', date('Y-m-d'));
1061 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
1062 $day = substr($fixed_period_start_day, -2) . "<br>";
1063 $year = $date[0];
1064 $startDate = $year . '-' . $month . '-' . $day;
1065 }
1066 else {
1067 $startDate = date('Y-m-d');
1068 }
1069 }
1070
1071 $date = explode('-', $startDate);
1072 $year = $date[0];
1073 $month = $date[1];
1074 $day = $date[2];
1075
1076 switch ($duration_unit) {
1077 case 'year':
1078 $year = $year + $duration_interval;
1079 break;
1080
1081 case 'month':
1082 $month = $month + $duration_interval;
1083 break;
1084
1085 case 'day':
1086 $day = $day + $duration_interval;
1087 break;
1088
1089 case 'week':
1090 $day = $day + ($duration_interval * 7);
1091 }
1092 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
1093 $this->assign('start_date', $startDate);
1094 $this->assign('end_date', $endDate);
1095 }
1096
1097 $dao = new CRM_Contribute_DAO_Premium();
1098 $dao->entity_table = 'civicrm_contribution_page';
1099 $dao->entity_id = $this->_id;
1100 $dao->find(TRUE);
1101 $this->assign('contact_phone', $dao->premiums_contact_phone);
1102 $this->assign('contact_email', $dao->premiums_contact_email);
1103
1104 //create Premium record
1105 $params = array(
1106 'product_id' => $premiumParams['selectProduct'],
1107 'contribution_id' => $contribution->id,
1108 'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
1109 'quantity' => 1,
1110 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
1111 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
1112 );
1113 if (!empty($premiumParams['selectProduct'])){
1114 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
1115 $daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
1116 $daoPremiumsProduct->premiums_id = $dao->id;
1117 $daoPremiumsProduct->find(true);
1118 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
1119 }
1120 //Fixed For CRM-3901
1121 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1122 $daoContrProd->contribution_id = $contribution->id;
1123 if ($daoContrProd->find(TRUE)) {
1124 $params['id'] = $daoContrProd->id;
1125 }
1126
1127 CRM_Contribute_BAO_Contribution::addPremium($params);
1128 if ($productDAO->cost && !empty($params['financial_type_id'])) {
1129 $trxnParams = array(
1130 'cost' => $productDAO->cost,
1131 'currency' => $productDAO->currency,
1132 'financial_type_id' => $params['financial_type_id'],
1133 'contributionId' => $contribution->id
1134 );
1135 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
1136 }
1137 }
1138 elseif ($selectProduct == 'no_thanks') {
1139 //Fixed For CRM-3901
1140 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1141 $daoContrProd->contribution_id = $contribution->id;
1142 if ($daoContrProd->find(TRUE)) {
1143 $daoContrProd->delete();
1144 }
1145 }
1146 }
1147
1148 /**
1149 * Process the contribution
1150 *
1151 * @param $form
1152 * @param array $params
1153 * @param array $result
1154 * @param integer $contactID
1155 * @param CRM_Financial_DAO_FinancialType $financialType
1156 * @param bool $pending
1157 * @param bool $online
1158 *
1159 * @param bool $isTest
1160 * @param array $lineItems
1161 *
1162 * @throws Exception
1163 * @return CRM_Contribute_DAO_Contribution
1164 * @access public
1165 */
1166 static function processContribution(
1167 &$form,
1168 $params,
1169 $result,
1170 $contactID,
1171 $financialType,
1172 $pending,
1173 $online,
1174 $isTest,
1175 $lineItems
1176 ) {
1177 $transaction = new CRM_Core_Transaction();
1178 $contribSoftContactId = $addressID = NULL;
1179
1180 // add these values for the recurringContrib function ,CRM-10188
1181 $params['financial_type_id'] = $financialType->id;
1182
1183 //create an contribution address
1184 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
1185 $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
1186 }
1187
1188 //@todo - this is being set from the form to resolve CRM-10188 - an
1189 // eNotice caused by it not being set @ the front end
1190 // however, we then get it being over-written with null for backend contributions
1191 // a better fix would be to set the values in the respective forms rather than require
1192 // a function being shared by two forms to deal with their respective values
1193 // moving it to the BAO & not taking the $form as a param would make sense here.
1194 if(!isset($params['is_email_receipt']) && !empty($form->_values['is_email_receipt'])){
1195 $params['is_email_receipt'] = CRM_Utils_Array::value( 'is_email_receipt', $form->_values );
1196 }
1197 $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
1198
1199 // CRM-11885
1200 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1201 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1202 $nonDeductibleAmount = $params['non_deductible_amount'];
1203 }
1204 // if non_deductible_amount does NOT exist - then calculate it depending on:
1205 // $contributionType->is_deductible and whether there is a product (premium).
1206 else {
1207 //if ($contributionType->is_deductible && $deductibleMode) {
1208 if ($financialType->is_deductible) {
1209 if ($online && isset($params['selectProduct'])) {
1210 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
1211 }
1212 if (!$online && isset($params['product_name'][0])) {
1213 $selectProduct = $params['product_name'][0];
1214 }
1215 // if there is a product - compare the value to the contribution amount
1216 if (isset($selectProduct) &&
1217 $selectProduct != 'no_thanks'
1218 ) {
1219 $productDAO = new CRM_Contribute_DAO_Product();
1220 $productDAO->id = $selectProduct;
1221 $productDAO->find(TRUE);
1222 // product value exceeds contribution amount
1223 if ($params['amount'] < $productDAO->price) {
1224 $nonDeductibleAmount = $params['amount'];
1225 }
1226 // product value does NOT exceed contribution amount
1227 else {
1228 $nonDeductibleAmount = $productDAO->price;
1229 }
1230 }
1231 // contribution is deductible - but there is no product
1232 else {
1233 $nonDeductibleAmount = '0.00';
1234 }
1235 }
1236 // contribution is NOT deductible
1237 else {
1238 $nonDeductibleAmount = $params['amount'];
1239 }
1240 }
1241
1242 $now = date('YmdHis');
1243 $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
1244 if (!empty($form->_values['is_email_receipt'])) {
1245 $receiptDate = $now;
1246 }
1247
1248 //get the contrib page id.
1249 $contributionPageId = NULL;
1250 if ($online) {
1251 $contributionPageId = $form->_id;
1252 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1253 if (!array_key_exists('campaign_id', $params)) {
1254 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1255 }
1256 }
1257 else {
1258 //also for offline we do support - CRM-7290
1259 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
1260 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1261 }
1262
1263 // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1264 if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
1265 // if its due to pcp
1266 if (!empty($params['pcp_made_through_id'])) {
1267 $contribSoftContactId = CRM_Core_DAO::getFieldValue(
1268 'CRM_PCP_DAO_PCP',
1269 $params['pcp_made_through_id'],
1270 'contact_id'
1271 );
1272 }
1273 else {
1274 $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
1275 }
1276
1277 // Pass these details onto with the contribution to make them
1278 // available at hook_post_process, CRM-8908
1279 $params['soft_credit_to'] = $contribSoftContactId;
1280 }
1281
1282 if (isset($params['amount'])) {
1283 $isMonetary = NULL;
1284 if (!empty($form->_values['is_monetary'])) {
1285 $isMonetary = $form->_values['is_monetary'];
1286 }
1287 $contribParams = self::getContributionParams(
1288 $params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate,
1289 $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems
1290 );
1291 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
1292 if (is_a($contribution, 'CRM_Core_Error')) {
1293 $message = CRM_Core_Error::getMessages($contribution);
1294 CRM_Core_Error::fatal($message);
1295 }
1296
1297 // lets store it in the form variable so postProcess hook can get to this and use it
1298 $form->_contributionID = $contribution->id;
1299 }
1300
1301 //CRM-13981, processing honor contact into soft-credit contribution
1302 CRM_Contact_Form_ProfileContact::postProcess($form);
1303
1304 // process soft credit / pcp pages
1305 CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
1306
1307 //handle pledge stuff.
1308 if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) &&
1309 (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))
1310 ) {
1311
1312 if (!empty($form->_values['pledge_id'])) {
1313
1314 //when user doing pledge payments.
1315 //update the schedule when payment(s) are made
1316 foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
1317 $scheduledAmount = CRM_Core_DAO::getFieldValue(
1318 'CRM_Pledge_DAO_PledgePayment',
1319 $paymentId,
1320 'scheduled_amount',
1321 'id'
1322 );
1323
1324 $pledgePaymentParams = array(
1325 'id' => $paymentId,
1326 'contribution_id' => $contribution->id,
1327 'status_id' => $contribution->contribution_status_id,
1328 'actual_amount' => $scheduledAmount,
1329 );
1330
1331
1332 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
1333 }
1334
1335 //update pledge status according to the new payment statuses
1336 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
1337 }
1338 else {
1339 //when user creating pledge record.
1340 $pledgeParams = array();
1341 $pledgeParams['contact_id'] = $contribution->contact_id;
1342 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
1343 $pledgeParams['contribution_id'] = $contribution->id;
1344 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
1345 $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
1346 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
1347 $pledgeParams['installments'] = $params['pledge_installments'];
1348 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
1349 if ($pledgeParams['frequency_unit'] == 'month') {
1350 $pledgeParams['frequency_day'] = intval(date("d"));
1351 }
1352 else {
1353 $pledgeParams['frequency_day'] = 1;
1354 }
1355 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
1356 $pledgeParams['status_id'] = $contribution->contribution_status_id;
1357 $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
1358 $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
1359 $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
1360 $pledgeParams['is_test'] = $contribution->is_test;
1361 $pledgeParams['acknowledge_date'] = date('Ymd');
1362 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
1363
1364 //inherit campaign from contirb page.
1365 $pledgeParams['campaign_id'] = $campaignId;
1366
1367 $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
1368
1369 $form->_params['pledge_id'] = $pledge->id;
1370
1371 //send acknowledgment email. only when pledge is created
1372 if ($pledge->id) {
1373 //build params to send acknowledgment.
1374 $pledgeParams['id'] = $pledge->id;
1375 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
1376 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
1377
1378 //scheduled amount will be same as installment_amount.
1379 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
1380
1381 //get total pledge amount.
1382 $pledgeParams['total_pledge_amount'] = $pledge->amount;
1383
1384 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
1385 }
1386 }
1387 }
1388
1389 if ($online && $contribution) {
1390 CRM_Core_BAO_CustomValueTable::postProcess($form->_params,
1391 CRM_Core_DAO::$_nullArray,
1392 'civicrm_contribution',
1393 $contribution->id,
1394 'Contribution'
1395 );
1396 }
1397 elseif ($contribution) {
1398 //handle custom data.
1399 $params['contribution_id'] = $contribution->id;
1400 if (!empty($params['custom']) &&
1401 is_array($params['custom']) &&
1402 !is_a($contribution, 'CRM_Core_Error')
1403 ) {
1404 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1405 }
1406 }
1407 // Save note
1408 if ($contribution && !empty($params['contribution_note'])) {
1409 $noteParams = array(
1410 'entity_table' => 'civicrm_contribution',
1411 'note' => $params['contribution_note'],
1412 'entity_id' => $contribution->id,
1413 'contact_id' => $contribution->contact_id,
1414 'modified_date' => date('Ymd'),
1415 );
1416
1417 CRM_Core_BAO_Note::add($noteParams, array());
1418 }
1419
1420
1421 if (isset($params['related_contact'])) {
1422 $contactID = $params['related_contact'];
1423 }
1424 elseif (isset($params['cms_contactID'])) {
1425 $contactID = $params['cms_contactID'];
1426 }
1427
1428 //create contribution activity w/ individual and target
1429 //activity w/ organisation contact id when onbelf, CRM-4027
1430 $targetContactID = NULL;
1431 if (!empty($params['hidden_onbehalf_profile'])) {
1432 $targetContactID = $contribution->contact_id;
1433 $contribution->contact_id = $contactID;
1434 }
1435
1436 // create an activity record
1437 if ($contribution) {
1438 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
1439 }
1440
1441 $transaction->commit();
1442 // CRM-13074 - create the CMSUser after the transaction is completed as it
1443 // is not appropriate to delete a valid contribution if a user create problem occurs
1444 CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params,
1445 $contactID,
1446 'email-' . $form->_bltID
1447 );
1448 return $contribution;
1449 }
1450
1451 /**
1452 * Create the recurring contribution record
1453 *
1454 */
1455 static function processRecurringContribution(&$form, &$params, $contactID, $contributionType, $online = TRUE) {
1456 // return if this page is not set for recurring
1457 // or the user has not chosen the recurring option
1458
1459 //this is online case validation.
1460 if ((empty($form->_values['is_recur']) && $online) || empty($params['is_recur'])) {
1461 return NULL;
1462 }
1463
1464 $recurParams = array('contact_id' => $contactID);
1465 $recurParams['amount'] = CRM_Utils_Array::value('amount', $params);
1466 $recurParams['auto_renew'] = CRM_Utils_Array::value('auto_renew', $params);
1467 $recurParams['frequency_unit'] = CRM_Utils_Array::value('frequency_unit', $params);
1468 $recurParams['frequency_interval'] = CRM_Utils_Array::value('frequency_interval', $params);
1469 $recurParams['installments'] = CRM_Utils_Array::value('installments', $params);
1470 $recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params);
1471
1472 // CRM-14354: For an auto-renewing membership with an additional contribution,
1473 // if separate payments is not enabled, make sure only the membership fee recurs
1474 if (!empty($form->_membershipBlock)
1475 && $form->_membershipBlock['is_separate_payment'] === '0'
1476 && isset($params['selectMembership'])
1477 && $form->_values['is_allow_other_amount'] == '1'
1478 ) {
1479 $recurParams['amount'] = $form->_membershipTypeValues[$params['selectMembership']]['minimum_fee'];
1480 }
1481
1482 $recurParams['is_test'] = 0;
1483 if (($form->_action & CRM_Core_Action::PREVIEW) ||
1484 (isset($form->_mode) && ($form->_mode == 'test'))
1485 ) {
1486 $recurParams['is_test'] = 1;
1487 }
1488
1489 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1490 if (!empty($params['receive_date'])) {
1491 $recurParams['start_date'] = $params['receive_date'];
1492 }
1493 $recurParams['invoice_id'] = CRM_Utils_Array::value('invoiceID', $params);
1494 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1495 $recurParams['payment_processor_id'] = CRM_Utils_Array::value('payment_processor_id', $params);
1496 $recurParams['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params);
1497 // we need to add a unique trxn_id to avoid a unique key error
1498 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1499 $recurParams['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params, $params['invoiceID']);
1500 $recurParams['financial_type_id'] = $contributionType->id;
1501
1502 if (!$online || $form->_values['is_monetary']) {
1503 $recurParams['payment_instrument_id'] = 1;
1504 }
1505
1506 $campaignId = CRM_Utils_Array::value('campaign_id', $params);
1507 if ($online) {
1508 if (!array_key_exists('campaign_id', $params)) {
1509 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
1510 }
1511 }
1512 $recurParams['campaign_id'] = $campaignId;
1513
1514 $recurring = CRM_Contribute_BAO_ContributionRecur::add($recurParams);
1515 if (is_a($recurring, 'CRM_Core_Error')) {
1516 CRM_Core_Error::displaySessionError($recurring);
1517 $urlString = 'civicrm/contribute/transact';
1518 $urlParams = '_qf_Main_display=true';
1519 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1520 $urlString = 'civicrm/contact/view/contribution';
1521 $urlParams = "action=add&cid={$form->_contactID}";
1522 if ($form->_mode) {
1523 $urlParams .= "&mode={$form->_mode}";
1524 }
1525 }
1526 CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
1527 }
1528
1529 return $recurring->id;
1530 }
1531
1532 /**
1533 * Function to add on behalf of organization and it's location
1534 *
1535 * @param $behalfOrganization array array of organization info
1536 * @param $contactID int individual contact id. One
1537 * who is doing the process of signup / contribution.
1538 *
1539 * @param $values array form values array
1540 * @param $params
1541 * @param null $fields
1542 *
1543 * @return void
1544 * @access public
1545 */
1546 static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1547 $isCurrentEmployer = FALSE;
1548 $dupeIDs = array();
1549 $orgID = NULL;
1550 if (!empty($behalfOrganization['organization_id']) && empty($behalfOrganization['org_option'])) {
1551 $orgID = $behalfOrganization['organization_id'];
1552 unset($behalfOrganization['organization_id']);
1553 $isCurrentEmployer = TRUE;
1554 }
1555
1556 // formalities for creating / editing organization.
1557 $behalfOrganization['contact_type'] = 'Organization';
1558
1559 // get the relationship type id
1560 $relType = new CRM_Contact_DAO_RelationshipType();
1561 $relType->name_a_b = 'Employee of';
1562 $relType->find(TRUE);
1563 $relTypeId = $relType->id;
1564
1565 // keep relationship params ready
1566 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1567 $relParams['is_permission_a_b'] = 1;
1568 $relParams['is_active'] = 1;
1569
1570 if (!$orgID) {
1571 // check if matching organization contact exists
1572 $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization');
1573 $dedupeParams['check_permission'] = FALSE;
1574 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
1575
1576 // CRM-6243 says to pick the first org even if more than one match
1577 if (count($dupeIDs) >= 1) {
1578 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1579 // don't allow name edit
1580 unset($behalfOrganization['organization_name']);
1581 }
1582 }
1583 else {
1584 // if found permissioned related organization, allow location edit
1585 $behalfOrganization['contact_id'] = $orgID;
1586 // don't allow name edit
1587 unset($behalfOrganization['organization_name']);
1588 }
1589
1590 // handling for image url
1591 if (!empty($behalfOrganization['image_URL'])) {
1592 CRM_Contact_BAO_Contact::processImageParams($behalfOrganization);
1593 }
1594
1595 // create organization, add location
1596 $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID,
1597 NULL, NULL, 'Organization'
1598 );
1599 // create relationship
1600 $relParams['contact_check'][$orgID] = 1;
1601 $cid = array('contact' => $contactID);
1602 CRM_Contact_BAO_Relationship::create($relParams, $cid);
1603
1604 // if multiple match - send a duplicate alert
1605 if ($dupeIDs && (count($dupeIDs) > 1)) {
1606 $values['onbehalf_dupe_alert'] = 1;
1607 // required for IPN
1608 $params['onbehalf_dupe_alert'] = 1;
1609 }
1610
1611 // make sure organization-contact-id is considered for recording
1612 // contribution/membership etc..
1613 if ($contactID != $orgID) {
1614 // take a note of contact-id, so we can send the
1615 // receipt to individual contact as well.
1616
1617 // required for mailing/template display ..etc
1618 $values['related_contact'] = $contactID;
1619 // required for IPN
1620 $params['related_contact'] = $contactID;
1621
1622 //make this employee of relationship as current
1623 //employer / employee relationship, CRM-3532
1624 if ($isCurrentEmployer &&
1625 ($orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1626 ) {
1627 $isCurrentEmployer = FALSE;
1628 }
1629
1630 if (!$isCurrentEmployer && $orgID) {
1631 //build current employer params
1632 $currentEmpParams[$contactID] = $orgID;
1633 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
1634 }
1635
1636 // contribution / signup will be done using this
1637 // organization id.
1638 $contactID = $orgID;
1639 }
1640 }
1641
1642 /**
1643 * Function used to save pcp / soft credit entry
1644 * This is used by contribution and also event pcps
1645 *
1646 * @param array $params associated array
1647 * @param object $contribution contribution object
1648 *
1649 * @static
1650 * @access public
1651 */
1652 static function processPcpSoft(&$params, &$contribution) {
1653 //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
1654 if (!empty($params['soft_credit_to'])) {
1655 $contributionSoftParams = array();
1656 foreach (array(
1657 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) {
1658 if (!empty($params[$val])) {
1659 $contributionSoftParams[$val] = $params[$val];
1660 }
1661 }
1662
1663 $contributionSoftParams['contact_id'] = $params['soft_credit_to'];
1664 // add contribution id
1665 $contributionSoftParams['contribution_id'] = $contribution->id;
1666 // add pcp id
1667 $contributionSoftParams['pcp_id'] = $params['pcp_made_through_id'];
1668
1669 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
1670
1671 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
1672 }
1673 }
1674
1675 /**
1676 * Function used to se pcp related defaults / params
1677 * This is used by contribution and also event pcps
1678 *
1679 * @param object $page form object
1680 * @param array $params associated array
1681 *
1682 * @return array
1683 * @static
1684 * @access public
1685 */
1686 static function processPcp(&$page, $params) {
1687 $params['pcp_made_through_id'] = $page->_pcpId;
1688 $page->assign('pcpBlock', TRUE);
1689 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1690 $params['pcp_roll_nickname'] = ts('Anonymous');
1691 $params['pcp_is_anonymous'] = 1;
1692 }
1693 else {
1694 $params['pcp_is_anonymous'] = 0;
1695 }
1696 foreach (array(
1697 'pcp_display_in_roll',
1698 'pcp_is_anonymous',
1699 'pcp_roll_nickname',
1700 'pcp_personal_note'
1701 ) as $val) {
1702 if (!empty($params[$val])) {
1703 $page->assign($val, $params[$val]);
1704 }
1705 }
1706
1707 return $params;
1708 }
1709
1710 /**
1711 * @param array $membershipParams
1712 * @param integer $contactID
1713 * @param array $customFieldsFormatted
1714 * @param array $fieldTypes
1715 * @param array $premiumParams
1716 * @param array $membershipLineItems line items specifically relating to memberships
1717 */
1718 public function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems) {
1719 try {
1720 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1721 $membershipTypes = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIDs);
1722 $membershipType = empty($membershipTypes) ? array() : reset($membershipTypes);
1723 $this->assign('membership_name', CRM_Utils_Array::value('name', $membershipType));
1724
1725 $isPaidMembership = FALSE;
1726 if($this->_amount >= 0.0 && isset($membershipParams['amount'])) {
1727 //amount must be greater than zero for
1728 //adding contribution record to contribution table.
1729 //this condition arises when separate membership payment is
1730 //enabled and contribution amount is not selected. fix for CRM-3010
1731 $isPaidMembership = TRUE;
1732 }
1733 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id, $this->_values['amount_block_is_active']);
1734
1735 if ($this->_values['amount_block_is_active']) {
1736 $contributionTypeId = $this->_values['financial_type_id'];
1737 }
1738 else {
1739 $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipType, CRM_Utils_Array::value('financial_type_id' ,$membershipParams));
1740 }
1741
1742 CRM_Member_BAO_Membership::postProcessMembership($membershipParams, $contactID,
1743 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId, $isProcessSeparateMembershipTransaction, $contributionTypeId,
1744 $membershipLineItems
1745 );
1746 $this->assign('membership_assign', TRUE);
1747 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1748 }
1749 catch (CRM_Core_Exception $e) {
1750 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1751 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
1752 }
1753 }
1754
1755 /**
1756 * Are we going to do 2 financial transactions?
1757 * ie the membership block supports a separate transactions AND the contribution form has been configured for a contribution
1758 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferPayment style)
1759 *
1760 *
1761 * @param integer $formID
1762 * @param bool $amountBlockActiveOnForm
1763 *
1764 * @return bool
1765 */
1766 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1767 $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($formID);
1768 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1769 return TRUE;
1770 }
1771 return FALSE;
1772 }
1773
1774 /**
1775 * This function sets the fields
1776 * - $this->_params['amount_level']
1777 * - $this->_params['selectMembership']
1778 * And under certain circumstances sets
1779 * $this->_params['amount'] = null;
1780 *
1781 * @param $priceSetID
1782 *
1783 * @internal param $isQuickConfig
1784 * @internal param $priceField
1785 */
1786 public function setFormAmountFields($priceSetID) {
1787 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config');
1788 $priceField = new CRM_Price_DAO_PriceField();
1789 $priceField->price_set_id = $priceSetID;
1790 $priceField->orderBy('weight');
1791 $priceField->find();
1792 $paramWeDoNotUnderstand = NULL;
1793
1794 while ($priceField->fetch()) {
1795 if ($priceField->name == "contribution_amount") {
1796 $paramWeDoNotUnderstand = $priceField->id;
1797 }
1798 if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) {
1799 if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') {
1800 $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1801 $this->_params["price_{$priceField->id}"], 'label');
1802 }
1803 if ($priceField->name == "membership_amount") {
1804 $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1805 $this->_params["price_{$priceField->id}"], 'membership_type_id');
1806 }
1807 } // if separate payment we set contribution amount to be null, so that it will not show contribution amount same as membership amount.
1808 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1809 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1810 // so we should merge them together
1811 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1812 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1813 elseif (
1814 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock)
1815 && !empty($this->_values['fee'][$priceField->id])
1816 && ($this->_values['fee'][$priceField->id]['name'] == "other_amount")
1817 && CRM_Utils_Array::value("price_{$paramWeDoNotUnderstand}", $this->_params) < 1
1818 && empty($this->_params["price_{$priceField->id}"])
1819 ) {
1820 $this->_params['amount'] = null;
1821 }
1822
1823 // Fix for CRM-14375 - If we are using separate payments and "no
1824 // thank you" is selected for the additional contribution, set
1825 // contribution amount to be null, so that it will not show
1826 // contribution amount same as membership amount.
1827 //@todo - merge with section above
1828 if ($this->_membershipBlock['is_separate_payment']
1829 && !empty($this->_values['fee'][$priceField->id])
1830 && CRM_Utils_Array::value('name', $this->_values['fee'][$priceField->id]) == 'contribution_amount'
1831 && CRM_Utils_Array::value("price_{$priceField->id}", $this->_params) == '-1'
1832 ) {
1833 $this->_params['amount'] = null;
1834 }
1835 }
1836 }
1837
1838 static function submit($params) {
1839 $form = new CRM_Contribute_Form_Contribution_Confirm();
1840 $form->_id = $params['id'];
1841 if (!empty($params['contact_id'])) {
1842 $form->_contactID = $params['contact_id'];
1843 }
1844 CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
1845 $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
1846 //this way the mocked up controller ignores the session stuff
1847 $_SERVER['REQUEST_METHOD'] = 'GET';
1848 $form->controller = new CRM_Contribute_Controller_Contribution();
1849 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1850 $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
1851 $form->_amount = $params['amount'];
1852 $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1853 $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
1854 $priceSetFields = reset($priceFields);
1855 $form->_values['fee'] = $priceSetFields['fields'];
1856 $form->_priceSetId = $priceSetID;
1857 $form->setFormAmountFields($priceSetID);
1858 if (!empty($params['payment_processor'])) {
1859 $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array('id' => $params['payment_processor']));
1860 if ($form->_paymentProcessor['billing_mode'] ==1) {
1861 $form->_contributeMode = 'direct';
1862 }
1863 else {
1864 $form->_contributeMode = 'notify';
1865 }
1866 }
1867 $priceFields = $priceFields[$priceSetID]['fields'];
1868 CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
1869 $form->_lineItem = array($priceSetID => $lineItems);
1870 $form->postProcess();
1871 }
1872
1873 /**
1874 * Helper function for static submit function - set relevant params - help us to build up an array that we can pass in
1875 * @param $id
1876 * @param array $params
1877 *
1878 * @return array
1879 * @throws CiviCRM_API3_Exception
1880 */
1881 static function getFormParams($id, array $params) {
1882 if(!isset($params['is_pay_later'])) {
1883 if (!empty($params['payment_processor'])) {
1884 $params['is_pay_later'] = 0;
1885 }
1886 else {
1887 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array(
1888 'id' => $id,
1889 'return' => 'is_pay_later'
1890 ));
1891 }
1892 }
1893 if(empty($params['price_set_id'])) {
1894 $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
1895 }
1896 return $params;
1897 }
1898 }