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