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