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