Newer
Older
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
*/
/**
* form to process actions on the group aspect of Custom Data
*/
class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_ContributionBase {
/**
* The id of the contact associated with this contribution.
*
* @var int
*/
public $_contactID;
/**
* The id of the contribution object that is created when the form is submitted.
*
* @var int
*/
public $_contributionID;
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/**
* @param $form
* @param $params
* @param $contributionParams
* @param $pledgeID
* @param $contribution
* @param $isEmailReceipt
* @return mixed
*/
public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
if ($pledgeID) {
//when user doing pledge payments.
//update the schedule when payment(s) are made
$amount = $params['amount'];
$pledgePaymentParams = array();
foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
$scheduledAmount = CRM_Core_DAO::getFieldValue(
'CRM_Pledge_DAO_PledgePayment',
$paymentId,
'scheduled_amount',
'id'
);
$pledgePayment = ($amount >= $scheduledAmount) ? $scheduledAmount : $amount;
if ($pledgePayment > 0) {
$pledgePaymentParams[] = array(
'id' => $paymentId,
'contribution_id' => $contribution->id,
'status_id' => $contribution->contribution_status_id,
'actual_amount' => $pledgePayment,
);
$amount -= $pledgePayment;
}
}
if ($amount > 0 && count($pledgePaymentParams)) {
$pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount;
}
foreach ($pledgePaymentParams as $p) {
CRM_Pledge_BAO_PledgePayment::add($p);
}
//update pledge status according to the new payment statuses
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
return $form;
}
else {
//when user creating pledge record.
$pledgeParams = array();
$pledgeParams['contact_id'] = $contribution->contact_id;
$pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
$pledgeParams['contribution_id'] = $contribution->id;
$pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
$pledgeParams['financial_type_id'] = $contribution->financial_type_id;
$pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
$pledgeParams['installments'] = $params['pledge_installments'];
$pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
if ($pledgeParams['frequency_unit'] == 'month') {
$pledgeParams['frequency_day'] = intval(date("d"));
}
else {
$pledgeParams['frequency_day'] = 1;
}
$pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
if (CRM_Utils_Array::value('start_date', $params)) {
$pledgeParams['frequency_day'] = intval(date("d", strtotime(CRM_Utils_Array::value('start_date', $params))));
$pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime(CRM_Utils_Array::value('start_date', $params)));
}
$pledgeParams['status_id'] = $contribution->contribution_status_id;
$pledgeParams['max_reminders'] = $form->_values['max_reminders'];
$pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
$pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
$pledgeParams['is_test'] = $contribution->is_test;
$pledgeParams['acknowledge_date'] = date('Ymd');
$pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
//inherit campaign from contirb page.
$pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams);
$pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
$form->_params['pledge_id'] = $pledge->id;
//send acknowledgment email. only when pledge is created
if ($pledge->id && $isEmailReceipt) {
//build params to send acknowledgment.
$pledgeParams['id'] = $pledge->id;
$pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
$pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
//scheduled amount will be same as installment_amount.
$pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
//get total pledge amount.
$pledgeParams['total_pledge_amount'] = $pledge->amount;
CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
return $form;
}
return $form;
}
}
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* Set the parameters to be passed to contribution create function.
*
* @param array $params
* @param int $financialTypeID
* @param float $nonDeductibleAmount
* @param bool $pending
* @param array $paymentProcessorOutcome
* @param string $receiptDate
* @param int $recurringContributionID
*
* @return array
*/
public static function getContributionParams(
$params, $financialTypeID, $nonDeductibleAmount, $pending,
$paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
$contributionParams = array(
'financial_type_id' => $financialTypeID,
'receive_date' => (CRM_Utils_Array::value('receive_date', $params)) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'),
'non_deductible_amount' => $nonDeductibleAmount,
'total_amount' => $params['amount'],
'tax_amount' => CRM_Utils_Array::value('tax_amount', $params),
'amount_level' => CRM_Utils_Array::value('amount_level', $params),
'invoice_id' => $params['invoiceID'],
'currency' => $params['currencyID'],
'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
//configure cancel reason, cancel date and thankyou date
//from 'contribution' type profile if included
'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0),
'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL,
'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL,
//setting to make available to hook - although seems wrong to set on form for BAO hook availability
'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0),
);
if ($paymentProcessorOutcome) {
$contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
}
if (!$pending && $paymentProcessorOutcome) {
$contributionParams += array(
'fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome),
'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']),
'trxn_id' => $paymentProcessorOutcome['trxn_id'],
'receipt_date' => $receiptDate,
// also add financial_trxn details as part of fix for CRM-4724
'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome),
);
}
// CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
$contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
$contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
if ($recurringContributionID) {
$contributionParams['contribution_recur_id'] = $recurringContributionID;
}
$contributionParams['contribution_status_id'] = $pending ? 2 : 1;
if (isset($contributionParams['invoice_id'])) {
$contributionParams['id'] = CRM_Core_DAO::getFieldValue(
'CRM_Contribute_DAO_Contribution',
$contributionParams['invoice_id'],
'id',
'invoice_id'
);
}
return $contributionParams;
}
/**
* Get non-deductible amount.
*
* This is a bit too much about wierd form interpretation to be this deep.
*
* CRM-11885
* if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
* it.
*
* @param array $params
* @param CRM_Financial_BAO_FinancialType $financialType
* @param bool $online
* @param CRM_Contribute_Form_Contribution_Confirm $form
protected static function getNonDeductibleAmount($params, $financialType, $online, $form) {
if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
return $params['non_deductible_amount'];
}
$priceSetId = CRM_Utils_Array::value('priceSetId', $params);
// return non-deductible amount if it is set at the price field option level
if ($priceSetId && !empty($form->_lineItem)) {
$nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem);
}
if (!empty($nonDeductibleAmount)) {
return $nonDeductibleAmount;
}
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
else {
if ($financialType->is_deductible) {
if ($online && isset($params['selectProduct'])) {
$selectProduct = CRM_Utils_Array::value('selectProduct', $params);
}
if (!$online && isset($params['product_name'][0])) {
$selectProduct = $params['product_name'][0];
}
// if there is a product - compare the value to the contribution amount
if (isset($selectProduct) &&
$selectProduct != 'no_thanks'
) {
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $selectProduct;
$productDAO->find(TRUE);
// product value exceeds contribution amount
if ($params['amount'] < $productDAO->price) {
$nonDeductibleAmount = $params['amount'];
return $nonDeductibleAmount;
}
// product value does NOT exceed contribution amount
else {
return $productDAO->price;
}
}
// contribution is deductible - but there is no product
else {
return '0.00';
}
}
// contribution is NOT deductible
else {
return $params['amount'];
}
}
}
/**
* Set variables up before form is built.
*/
public function preProcess() {
$config = CRM_Core_Config::singleton();
parent::preProcess();
// lineItem isn't set until Register postProcess
$this->_lineItem = $this->get('lineItem');
$this->_paymentProcessor = $this->get('paymentProcessor');
$this->_params = $this->controller->exportValues('Main');
$this->_params['ip_address'] = CRM_Utils_System::ipAddress();
$this->_params['amount'] = $this->get('amount');
if (isset($this->_params['amount'])) {
$this->setFormAmountFields($this->_params['priceSetId']);
}
$this->_params['tax_amount'] = $this->get('tax_amount');
$this->_useForMember = $this->get('useForMember');
if (isset($this->_params['credit_card_exp_date'])) {
$this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
$this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
}
$this->_params['currencyID'] = $config->defaultCurrency;
if (!empty($this->_membershipBlock)) {
$this->_params['selectMembership'] = $this->get('selectMembership');
}
if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
$preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
$this->_params = array_merge($this->_params, $preApprovalParams);
// We may have fetched some billing details from the getPreApprovalDetails function so we
// want to ensure we set this after that function has been called.
CRM_Core_Payment_Form::mapParams($this->_bltID, $preApprovalParams, $this->_params, FALSE);
}
$this->_params['is_pay_later'] = $this->get('is_pay_later');
$this->assign('is_pay_later', $this->_params['is_pay_later']);
if ($this->_params['is_pay_later']) {
$this->assign('pay_later_receipt', CRM_Utils_Array::value('pay_later_receipt', $this->_values));
}
// if onbehalf-of-organization
if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
$this->_params['organization_id'] = CRM_Utils_Array::value('onbehalfof_id', $this->_params);
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
$this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
$addressBlocks = array(
'street_address',
'city',
'state_province',
'postal_code',
'country',
'supplemental_address_1',
'supplemental_address_2',
'supplemental_address_3',
'postal_code_suffix',
'geo_code_1',
'geo_code_2',
'address_name',
);
$blocks = array('email', 'phone', 'im', 'url', 'openid');
foreach ($this->_params['onbehalf'] as $loc => $value) {
$field = $typeId = NULL;
if (strstr($loc, '-')) {
list($field, $locType) = explode('-', $loc);
}
if (in_array($field, $addressBlocks)) {
if ($locType == 'Primary') {
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
$locType = $defaultLocationType->id;
}
if ($field == 'country') {
$value = CRM_Core_PseudoConstant::countryIsoCode($value);
}
elseif ($field == 'state_province') {
$value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
}
$isPrimary = 1;
if (isset($this->_params['onbehalf_location']['address'])
&& count($this->_params['onbehalf_location']['address']) > 0
) {
$isPrimary = 0;
}
$this->_params['onbehalf_location']['address'][$locType][$field] = $value;
if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) {
$this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
}
$this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
}
elseif (in_array($field, $blocks)) {
if (!$typeId || is_numeric($typeId)) {
$blockName = $fieldName = $field;
$locationType = 'location_type_id';
if ($locType == 'Primary') {
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
$locationValue = $defaultLocationType->id;
}
else {
$locationValue = $locType;
}
$locTypeId = '';
$phoneExtField = array();
if ($field == 'url') {
$blockName = 'website';
$locationType = 'website_type_id';
list($field, $locationValue) = explode('-', $loc);
}
elseif ($field == 'im') {
$fieldName = 'name';
$locTypeId = 'provider_id';
$typeId = $this->_params['onbehalf']["{$loc}-provider_id"];
}
elseif ($field == 'phone') {
list($field, $locType, $typeId) = explode('-', $loc);
$locTypeId = 'phone_type_id';
//check if extension field exists
$extField = str_replace('phone', 'phone_ext', $loc);
if (isset($this->_params['onbehalf'][$extField])) {
$phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]);
}
}
$isPrimary = 1;
if (isset ($this->_params['onbehalf_location'][$blockName])
&& count($this->_params['onbehalf_location'][$blockName]) > 0
) {
$isPrimary = 0;
}
if ($locationValue) {
$blockValues = array(
$fieldName => $value,
$locationType => $locationValue,
'is_primary' => $isPrimary,
);
if ($locTypeId) {
$blockValues = array_merge($blockValues, array($locTypeId => $typeId));
}
if (!empty($phoneExtField)) {
$blockValues = array_merge($blockValues, $phoneExtField);
}
$this->_params['onbehalf_location'][$blockName][] = $blockValues;
}
}
}
elseif (strstr($loc, 'custom')) {
if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) {
$value = $this->_params['onbehalf']["{$loc}_id"];
}
$this->_params['onbehalf_location']["{$loc}"] = $value;
}
else {
if ($loc == 'contact_sub_type') {
$this->_params['onbehalf_location'][$loc] = $value;
}
else {
$this->_params['onbehalf_location'][$field] = $value;
}
}
}
}
elseif (!empty($this->_values['is_for_organization'])) {
// no on behalf of an organization, CRM-5519
// so reset loc blocks from main params.
foreach (array(
'phone',
'email',
'address',
) as $blk) {
if (isset($this->_params[$blk])) {
unset($this->_params[$blk]);
}
}
}
$this->setRecurringMembershipParams();
if ($this->_pcpId) {
$params = $this->processPcp($this, $this->_params);
$this->_params = $params;
}
$this->_params['invoiceID'] = $this->get('invoiceID');
//carry campaign from profile.
if (array_key_exists('contribution_campaign_id', $this->_params)) {
$this->_params['campaign_id'] = $this->_params['contribution_campaign_id'];
}
// assign contribution page id to the template so we can add css class for it
$this->assign('contributionPageID', $this->_id);
$this->assign('is_for_organization', CRM_Utils_Array::value('is_for_organization', $this->_params));
$this->set('params', $this->_params);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->assignToTemplate();
$params = $this->_params;
// make sure we have values for it
if (!empty($this->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid)) {
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
$honorName = NULL;
$softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
$this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor']);
$fieldTypes = array('Contact');
$fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($this->_values['honoree_profile_id']);
$this->buildCustom($this->_values['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
}
$this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
$amount_block_is_active = $this->get('amount_block_is_active');
$this->assign('amount_block_is_active', $amount_block_is_active);
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
if ($invoicing) {
$getTaxDetails = FALSE;
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
foreach ($this->_lineItem as $key => $value) {
foreach ($value as $v) {
if (isset($v['tax_rate'])) {
if ($v['tax_rate'] != '') {
$getTaxDetails = TRUE;
}
}
}
}
$this->assign('getTaxDetails', $getTaxDetails);
$this->assign('taxTerm', $taxTerm);
$this->assign('totalTaxAmount', $params['tax_amount']);
}
if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
$option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params);
$productID = $params['selectProduct'];
CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE,
$productID, $option
);
$this->set('productID', $productID);
$this->set('option', $option);
}
$config = CRM_Core_Config::singleton();
if (in_array('CiviMember', $config->enableComponents) && empty($this->_ccid)) {
if (isset($params['selectMembership']) &&
$params['selectMembership'] != 'no_thanks'
) {
$this->buildMembershipBlock(
$this->_membershipContactID,
FALSE,
$params['selectMembership'],
FALSE
);
if (!empty($params['auto_renew'])) {
$this->assign('auto_renew', TRUE);
}
}
else {
$this->assign('membershipBlock', FALSE);
}
}
if (empty($this->_ccid)) {
$this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
$this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
}
if (!empty($this->_values['onbehalf_profile_id']) &&
!empty($params['onbehalf']) &&
($this->_values['is_for_organization'] == 2 ||
!empty($params['is_for_organization'])
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
$fieldTypes = array('Contact', 'Organization');
$contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
$fieldTypes = array_merge($fieldTypes, $contactSubType);
if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
$fieldTypes = array_merge($fieldTypes, array('Membership'));
}
else {
$fieldTypes = array_merge($fieldTypes, array('Contribution'));
}
$this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
}
$this->_separateMembershipPayment = $this->get('separateMembershipPayment');
$this->assign('is_separate_payment', $this->_separateMembershipPayment);
if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
$this->assign('lineItem', $this->_lineItem);
}
else {
$this->assign('is_quick_config', 1);
$this->_params['is_quick_config'] = 1;
}
$this->assign('priceSetID', $this->_priceSetId);
// The concept of contributeMode is deprecated.
// the is_monetary concept probably should be too as it can be calculated from
// the existence of 'amount' & seems fragile.
if ($this->_contributeMode == 'notify' ||
$this->_amount < 0.0 || $this->_params['is_pay_later'] ||
($this->_separateMembershipPayment && $this->_amount <= 0.0)
) {
$contribButton = ts('Continue');
$this->assign('button', ts('Continue'));
}
elseif (!empty($this->_ccid)) {
$contribButton = ts('Make Payment');
$this->assign('button', ts('Make Payment'));
}
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
else {
$contribButton = ts('Make Contribution');
$this->assign('button', ts('Make Contribution'));
}
$this->addButtons(array(
array(
'type' => 'next',
'name' => $contribButton,
'spacing' => ' ',
'isDefault' => TRUE,
'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
),
array(
'type' => 'back',
'name' => ts('Go Back'),
),
)
);
$defaults = array();
$fields = array_fill_keys(array_keys($this->_fields), 1);
$fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
$contact = $this->_params;
foreach ($fields as $name => $dontCare) {
// Recursively set defaults for nested fields
if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' || $name == 'honor')) {
foreach ($contact[$name] as $fieldName => $fieldValue) {
if (is_array($fieldValue) && !in_array($this->_fields[$name][$fieldName]['html_type'], array(
'Multi-Select',
'AdvMulti-Select',
))
) {
foreach ($fieldValue as $key => $value) {
$defaults["{$name}[{$fieldName}][{$key}]"] = $value;
}
}
else {
$defaults["{$name}[{$fieldName}]"] = $fieldValue;
}
}
}
elseif (isset($contact[$name])) {
$defaults[$name] = $contact[$name];
if (substr($name, 0, 7) == 'custom_') {
$timeField = "{$name}_time";
if (isset($contact[$timeField])) {
$defaults[$timeField] = $contact[$timeField];
}
if (isset($contact["{$name}_id"])) {
$defaults["{$name}_id"] = $contact["{$name}_id"];
}
}
elseif (in_array($name, array(
'addressee',
'email_greeting',
'postal_greeting',
)) && !empty($contact[$name . '_custom'])
) {
$defaults[$name . '_custom'] = $contact[$name . '_custom'];
}
}
}
$this->assign('useForMember', $this->get('useForMember'));
$this->setDefaults($defaults);
$this->freeze();
}
/**
* Overwrite action.
*
* Since we are only showing elements in frozen mode no help display needed.
*
* @return int
*/
public function getAction() {
if ($this->_action & CRM_Core_Action::PREVIEW) {
return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
}
else {
return CRM_Core_Action::VIEW;
}
}
/**
* Set default values for the form.
*
* Note that in edit/view mode
* the default values are retrieved from the database
*/
public function setDefaultValues() {
}
/**
* Process the form.
*/
public function postProcess() {
$contactID = $this->getContactID();
$result = $this->processFormSubmission($contactID);
if (is_array($result) && !empty($result['is_payment_failure'])) {
// We will probably have the function that gets this error throw an exception on the next round of refactoring.
CRM_Core_Session::singleton()->setStatus(ts("Payment Processor Error message :") .
$result['error']->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
"_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
));
}
// Presumably this is for hooks to access? Not quite clear & perhaps not required.
$this->set('params', $this->_params);
}
/**
* Wrangle financial type ID.
*
* 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
* Pledges are not relevant to the membership code so that portion will not go onto the membership form.
*
* Comments from previous refactor indicate doubt as to what was going on.
*
* @param int $contributionTypeId
*
* @return null|string
*/
public function wrangleFinancialTypeID($contributionTypeId) {
if (isset($paymentParams['financial_type'])) {
$contributionTypeId = $paymentParams['financial_type'];
}
elseif (!empty($this->_values['pledge_id'])) {
$contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
$this->_values['pledge_id'],
'financial_type_id'
);
}
return $contributionTypeId;
}
/**
* Process the form.
*
* @param array $premiumParams
* @param CRM_Contribute_BAO_Contribution $contribution
*/
protected function postProcessPremium($premiumParams, $contribution) {
$hour = $minute = $second = 0;
// assigning Premium information to receipt tpl
$selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
if ($selectProduct &&
$selectProduct != 'no_thanks'
) {
$startDate = $endDate = "";
$this->assign('selectPremium', TRUE);
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $selectProduct;
$productDAO->find(TRUE);
$this->assign('product_name', $productDAO->name);
$this->assign('price', $productDAO->price);
$this->assign('sku', $productDAO->sku);
$this->assign('option', CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams));
$periodType = $productDAO->period_type;
if ($periodType) {
$fixed_period_start_day = $productDAO->fixed_period_start_day;
$duration_unit = $productDAO->duration_unit;
$duration_interval = $productDAO->duration_interval;
if ($periodType == 'rolling') {
$startDate = date('Y-m-d');
}
elseif ($periodType == 'fixed') {
if ($fixed_period_start_day) {
$date = explode('-', date('Y-m-d'));
$month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
$day = substr($fixed_period_start_day, -2) . "<br/>";
$year = $date[0];
$startDate = $year . '-' . $month . '-' . $day;
}
else {
$startDate = date('Y-m-d');
}
}
$date = explode('-', $startDate);
$year = $date[0];
$month = $date[1];
$day = $date[2];
switch ($duration_unit) {
case 'year':
$year = $year + $duration_interval;
break;
case 'month':
$month = $month + $duration_interval;
break;
case 'day':
$day = $day + $duration_interval;
break;
case 'week':
$day = $day + ($duration_interval * 7);
}
$endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
$this->assign('start_date', $startDate);
$this->assign('end_date', $endDate);
}
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->find(TRUE);
$this->assign('contact_phone', $dao->premiums_contact_phone);
$this->assign('contact_email', $dao->premiums_contact_email);
//create Premium record
$params = array(
'product_id' => $premiumParams['selectProduct'],
'contribution_id' => $contribution->id,
'product_option' => CRM_Utils_Array::value('options_' . $premiumParams['selectProduct'], $premiumParams),
'quantity' => 1,
'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
);
if (!empty($premiumParams['selectProduct'])) {
$daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
$daoPremiumsProduct->product_id = $premiumParams['selectProduct'];
$daoPremiumsProduct->premiums_id = $dao->id;
$daoPremiumsProduct->find(TRUE);
$params['financial_type_id'] = $daoPremiumsProduct->financial_type_id;
}
//Fixed For CRM-3901
$daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
$daoContrProd->contribution_id = $contribution->id;
if ($daoContrProd->find(TRUE)) {
$params['id'] = $daoContrProd->id;
}
CRM_Contribute_BAO_Contribution::addPremium($params);
if ($productDAO->cost && !empty($params['financial_type_id'])) {
$trxnParams = array(
'cost' => $productDAO->cost,
'currency' => $productDAO->currency,
'financial_type_id' => $params['financial_type_id'],
'contributionId' => $contribution->id,
);
CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($trxnParams);
}
}
elseif ($selectProduct == 'no_thanks') {
//Fixed For CRM-3901
$daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
$daoContrProd->contribution_id = $contribution->id;
if ($daoContrProd->find(TRUE)) {
$daoContrProd->delete();
}
}
}
/**
* Process the contribution.
*
* @param CRM_Core_Form $form
* @param array $params
* @param array $result
* @param array $contributionParams
* Parameters to be passed to contribution create action.
* This differs from params in that we are currently adding params to it and 1) ensuring they are being
* passed consistently & 2) documenting them here.
* - contact_id
* - line_item
* - is_test
* - campaign_id
* - contribution_page_id
* - source
* - payment_type_id
* - thankyou_date (not all forms will set this)
*
* @param CRM_Financial_DAO_FinancialType $financialType
* @param bool $online
* Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
*
* @param int $billingLocationID
* ID of billing location type.
* @param bool $isRecur
* Is this recurring?
*
* @return \CRM_Contribute_DAO_Contribution
* @throws \Exception
*/
public static function processFormContribution(
&$form,
$params,
$result,
$contributionParams,
$financialType,
$online,
$billingLocationID,
$isRecur
) {
$transaction = new CRM_Core_Transaction();
$contactID = $contributionParams['contact_id'];
$isEmailReceipt = !empty($form->_values['is_email_receipt']);
$isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE;
$pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values);
if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
(!empty($params['is_pledge']) || $pledgeID)) {
$isPledge = TRUE;
}
else {
$isPledge = FALSE;
}
// add these values for the recurringContrib function ,CRM-10188
$params['financial_type_id'] = $financialType->id;
$contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
//@todo - this is being set from the form to resolve CRM-10188 - an
// eNotice caused by it not being set @ the front end
// however, we then get it being over-written with null for backend contributions
// a better fix would be to set the values in the respective forms rather than require
// a function being shared by two forms to deal with their respective values
// moving it to the BAO & not taking the $form as a param would make sense here.
if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
$params['is_email_receipt'] = $isEmailReceipt;
}
$params['is_recur'] = $isRecur;
$params['payment_instrument_id'] = $contributionParams['payment_instrument_id'];
$recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
$nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online, $form);
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$now = date('YmdHis');
$receiptDate = CRM_Utils_Array::value('receipt_date', $params);
if ($isEmailReceipt) {
$receiptDate = $now;
}
if (isset($params['amount'])) {
$contributionParams = array_merge(self::getContributionParams(
$params, $financialType->id, $nonDeductibleAmount, TRUE,
$result, $receiptDate,
$recurringContributionID), $contributionParams
);
$contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
if ($invoicing) {
$dataArray = array();
// @todo - interrogate the line items passed in on the params array.
// No reason to assume line items will be set on the form.
foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
foreach ($lineItemValue as $key => $value) {
if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
if (isset($dataArray[$value['tax_rate']])) {
$dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
}
else {
$dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
}
}
}
}
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('dataArray', $dataArray);
$smarty->assign('totalTaxAmount', $params['tax_amount']);
}
if (is_a($contribution, 'CRM_Core_Error')) {
$message = CRM_Core_Error::getMessages($contribution);
CRM_Core_Error::fatal($message);
}
// lets store it in the form variable so postProcess hook can get to this and use it
$form->_contributionID = $contribution->id;
}
// process soft credit / pcp params first
CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
//CRM-13981, processing honor contact into soft-credit contribution
CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);