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