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