CRM-16367 phpcs fixes
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 * This class generates form components for processing a contribution.
30 */
31 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
32 /**
33 * The id of the contribution that we are processing.
34 *
35 * @var int
36 */
37 public $_id;
38
39 /**
40 * The id of the premium that we are processing.
41 *
42 * @var int
43 */
44 public $_premiumID = NULL;
45
46 /**
47 * @var CRM_Contribute_DAO_ContributionProduct
48 */
49 public $_productDAO = NULL;
50
51 /**
52 * The id of the note.
53 *
54 * @var int
55 */
56 public $_noteID;
57
58 /**
59 * The id of the contact associated with this contribution.
60 *
61 * @var int
62 */
63 public $_contactID;
64
65 /**
66 * The id of the pledge payment that we are processing.
67 *
68 * @var int
69 */
70 public $_ppID;
71
72 /**
73 * Is this contribution associated with an online.
74 * financial transaction
75 *
76 * @var boolean
77 */
78 public $_online = FALSE;
79
80 /**
81 * Stores all product options.
82 *
83 * @var array
84 */
85 public $_options;
86
87 /**
88 * Storage of parameters from form
89 *
90 * @var array
91 */
92 public $_params;
93
94 /**
95 * Store the contribution Type ID
96 *
97 * @var array
98 */
99 public $_contributionType;
100
101 /**
102 * The contribution values if an existing contribution
103 */
104 public $_values;
105
106 /**
107 * The pledge values if this contribution is associated with pledge
108 */
109 public $_pledgeValues;
110
111 public $_contributeMode = 'direct';
112
113 public $_context;
114
115 /**
116 * Parameter with confusing name.
117 * @todo what is it?
118 * @var string
119 */
120 public $_compContext;
121
122 public $_compId;
123
124 /**
125 * Possible From email addresses
126 * @var array
127 */
128 public $_fromEmails;
129
130 /**
131 * ID of from email
132 * @var integer
133 */
134 public $fromEmailId;
135
136 /**
137 * Store the line items if price set used.
138 */
139 public $_lineItems;
140
141 /**
142 * Line item
143 * @todo explain why we use lineItem & lineItems
144 * @var array
145 */
146 public $_lineItem;
147
148 /**
149 * @var array soft credit info
150 */
151 public $_softCreditInfo;
152
153 protected $_formType;
154
155 /**
156 * @todo what on earth does cdType stand for????
157 * @var
158 */
159 protected $_cdType;
160 public $_honoreeProfileType;
161
162 /**
163 * Array of billing panes to be displayed by billingBlock.tpl.
164 * Currently this is likely to look like
165 * array('Credit Card' => ts('Credit Card') or
166 * array('Direct Debit => ts('Direct Debit')
167 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
168 *
169 * @var array
170 */
171 public $billingPane = array();
172
173 /**
174 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
175 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
176 *
177 * @var array
178 */
179 public $_paymentFields = array();
180 /**
181 * Logged in user's email.
182 * @var string
183 */
184 public $userEmail;
185
186 /**
187 * Price set ID
188 * @var integer
189 */
190 public $_priceSetId;
191
192
193 /**
194 * Price set as an array
195 * @var array
196 */
197 public $_priceSet;
198
199 /**
200 * Form defaults
201 * @todo can we define this a as protected? can we define higher up the chain
202 * @var array
203 */
204 public $_defaults;
205
206 /**
207 * User display name
208 *
209 * @var string
210 */
211 public $userDisplayName;
212
213 /**
214 * Status message to be shown to the user.
215 *
216 * @var array
217 */
218 protected $statusMessage = array();
219
220 /**
221 * Status message title to be shown to the user.
222 *
223 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
224 * although this might not be a good fit with the broad range of processors.
225 *
226 * @var string
227 */
228 protected $statusMessageTitle;
229
230 /**
231 * Set variables up before form is built.
232 */
233 public function preProcess() {
234
235 // Check permission for action.
236 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
237 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
238 }
239
240 // @todo - if anyone ever figures out what this _cdType subroutine is about
241 // (or even if it still applies) please add comments!!!!!!!!!!
242 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
243 $this->assign('cdType', FALSE);
244 if ($this->_cdType) {
245 $this->assign('cdType', TRUE);
246 CRM_Custom_Form_CustomData::preProcess($this);
247 return;
248 }
249
250 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
251
252 // Get price set id.
253 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
254 $this->set('priceSetId', $this->_priceSetId);
255 $this->assign('priceSetId', $this->_priceSetId);
256
257 // Get the pledge payment id
258 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
259
260 // Get the contact id
261 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
262
263 // Get the action.
264 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
265 $this->assign('action', $this->_action);
266
267 // Get the contribution id if update
268 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
269 if (!empty($this->_id)) {
270 $this->assign('contribID', $this->_id);
271 }
272
273 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
274 $this->assign('context', $this->_context);
275
276 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
277
278 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
279
280 //set the contribution mode.
281 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
282
283 $this->assign('contributionMode', $this->_mode);
284 if ($this->_action & CRM_Core_Action::DELETE) {
285 return;
286 }
287
288 $this->assign('showCheckNumber', TRUE);
289
290 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
291 $this->assignPaymentRelatedVariables();
292
293 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
294 $this->preProcessPledge();
295 }
296
297 if ($this->_id) {
298 $this->showRecordLinkMesssage($this->_id);
299 }
300 $this->_values = array();
301
302 // Current contribution id.
303 if ($this->_id) {
304 $this->assignPremiumProduct($this->_id);
305 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
306 }
307
308 // when custom data is included in this page
309 if (!empty($_POST['hidden_custom'])) {
310 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
311 }
312
313 $this->_lineItems = array();
314 if ($this->_id) {
315 if (!empty($this->_compId) && $this->_compContext == 'participant') {
316 $this->assign('compId', $this->_compId);
317 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
318 }
319 else {
320 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
321 }
322 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
323 }
324
325 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
326
327 // Set title
328 if ($this->_mode) {
329 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
330 }
331 else {
332 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
333 }
334
335 if ($this->_id) {
336 CRM_Contribute_Form_SoftCredit::preprocess($this);
337 }
338 }
339
340 /**
341 * Set default values.
342 *
343 * @return array
344 */
345 public function setDefaultValues() {
346 if ($this->_cdType) {
347 // @todo document when this function would be called in this way
348 // (and whether it is valid or an overloading of this form).
349 return CRM_Custom_Form_CustomData::setDefaultValues($this);
350 }
351
352 $defaults = $this->_values;
353
354 // Set defaults for pledge payment.
355 if ($this->_ppID) {
356 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
357 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
358 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
359 $defaults['option_type'] = 1;
360 }
361
362 if ($this->_action & CRM_Core_Action::DELETE) {
363 return $defaults;
364 }
365
366 $defaults['frequency_interval'] = 1;
367 $defaults['frequency_unit'] = 'month';
368
369 // Set soft credit defaults.
370 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
371
372 if ($this->_mode) {
373 $config = CRM_Core_Config::singleton();
374 // Set default country from config if no country set.
375 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
376 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
377 }
378
379 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
380 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
381 }
382
383 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
384 $defaults = array_merge($defaults, $billingDefaults);
385 }
386
387 if ($this->_id) {
388 $this->_contactID = $defaults['contact_id'];
389 }
390
391 // Set $newCredit variable in template to control whether link to credit card mode is included.
392 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
393
394 // Fix the display of the monetary value, CRM-4038.
395 if (isset($defaults['total_amount'])) {
396 if (!empty($defaults['tax_amount'])) {
397 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
398 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
399 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
400 }
401 }
402 else {
403 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
404 }
405 }
406
407 if (isset($defaults['non_deductible_amount'])) {
408 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
409 }
410
411 if (isset($defaults['fee_amount'])) {
412 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
413 }
414
415 if (isset($defaults['net_amount'])) {
416 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
417 }
418
419 if ($this->_contributionType) {
420 $defaults['financial_type_id'] = $this->_contributionType;
421 }
422
423 if (empty($defaults['payment_instrument_id'])) {
424 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
425 }
426
427 if (!empty($defaults['is_test'])) {
428 $this->assign('is_test', TRUE);
429 }
430
431 $this->assign('showOption', TRUE);
432 // For Premium section.
433 if ($this->_premiumID) {
434 $this->assign('showOption', FALSE);
435 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
436 if (!$options) {
437 $this->assign('showOption', TRUE);
438 }
439 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
440 if ($options_key) {
441 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
442 }
443 else {
444 $defaults['product_name'] = array($this->_productDAO->product_id);
445 }
446 if ($this->_productDAO->fulfilled_date) {
447 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
448 }
449 }
450
451 if (isset($this->userEmail)) {
452 $this->assign('email', $this->userEmail);
453 }
454
455 if (!empty($defaults['is_pay_later'])) {
456 $this->assign('is_pay_later', TRUE);
457 }
458 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
459
460 $dates = array(
461 'receive_date',
462 'receipt_date',
463 'cancel_date',
464 'thankyou_date',
465 );
466 foreach ($dates as $key) {
467 if (!empty($defaults[$key])) {
468 list($defaults[$key], $defaults[$key . '_time'])
469 = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime');
470 }
471 }
472
473 if (!$this->_id && empty($defaults['receive_date'])) {
474 list($defaults['receive_date'],
475 $defaults['receive_date_time']
476 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
477 }
478
479 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
480 CRM_Utils_Array::value('receive_date_time', $defaults)
481 ));
482 $currency = CRM_Utils_Array::value('currency', $defaults);
483 $this->assign('currency', $currency);
484 // Hack to get currency info to the js layer. CRM-11440.
485 CRM_Utils_Money::format(1);
486 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
487 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
488
489 // Inherit campaign from pledge.
490 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
491 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
492 }
493
494 $this->_defaults = $defaults;
495 return $defaults;
496 }
497
498 /**
499 * Build the form object.
500 */
501 public function buildQuickForm() {
502
503 //@todo document the purpose of cdType (if still in use)
504 if ($this->_cdType) {
505 CRM_Custom_Form_CustomData::buildQuickForm($this);
506 return;
507 }
508 $allPanes = array();
509 $recurJs = NULL;
510 //tax rate from financialType
511 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
512 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
513
514 // build price set form.
515 $buildPriceSet = FALSE;
516 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
517 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
518 $this->assign('invoicing', $invoicing);
519
520 // display tax amount on edit contribution page
521 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
522 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
523 }
524
525 if (empty($this->_lineItems) &&
526 ($this->_priceSetId || !empty($_POST['price_set_id']))
527 ) {
528 $buildPriceSet = TRUE;
529 $getOnlyPriceSetElements = TRUE;
530 if (!$this->_priceSetId) {
531 $this->_priceSetId = $_POST['price_set_id'];
532 $getOnlyPriceSetElements = FALSE;
533 }
534
535 $this->set('priceSetId', $this->_priceSetId);
536 CRM_Price_BAO_PriceSet::buildPriceSet($this);
537
538 // get only price set form elements.
539 if ($getOnlyPriceSetElements) {
540 return;
541 }
542 }
543 // use to build form during form rule.
544 $this->assign('buildPriceSet', $buildPriceSet);
545
546 $defaults = $this->_values;
547 $additionalDetailFields = array(
548 'note',
549 'thankyou_date',
550 'invoice_id',
551 'non_deductible_amount',
552 'fee_amount',
553 'net_amount',
554 );
555 foreach ($additionalDetailFields as $key) {
556 if (!empty($defaults[$key])) {
557 $defaults['hidden_AdditionalDetail'] = 1;
558 break;
559 }
560 }
561
562 if ($this->_productDAO) {
563 if ($this->_productDAO->product_id) {
564 $defaults['hidden_Premium'] = 1;
565 }
566 }
567
568 if ($this->_noteID &&
569 isset($this->_values['note'])
570 ) {
571 $defaults['hidden_AdditionalDetail'] = 1;
572 }
573
574 $paneNames = array(
575 ts('Additional Details') => 'AdditionalDetail',
576 );
577
578 //Add Premium pane only if Premium is exists.
579 $dao = new CRM_Contribute_DAO_Product();
580 $dao->is_active = 1;
581
582 if ($dao->find(TRUE)) {
583 $paneNames[ts('Premium Information')] = 'Premium';
584 }
585
586 $billingPanes = array();
587 if ($this->_mode) {
588 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE) == TRUE) {
589 foreach ($this->billingPane as $name => $label) {
590 if (!empty($this->billingFieldSets[$name]['fields'])) {
591 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
592 $billingPanes[$label] = $this->generatePane(CRM_Utils_String::convertStringToCamel($name), $defaults);
593 }
594 }
595 if (!empty($this->_recurPaymentProcessors)) {
596 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
597 $this->setDefaults(array('is_recur' => 0));
598 $this->assign('buildRecurBlock', TRUE);
599 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
600 }
601 }
602 }
603
604 foreach ($paneNames as $name => $type) {
605 $allPanes[$name] = $this->generatePane($type, $defaults);
606 }
607
608 $qfKey = $this->controller->_key;
609 $this->assign('qfKey', $qfKey);
610 $this->assign('billingPanes', $billingPanes);
611 $this->assign('allPanes', $allPanes);
612
613 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
614
615 if ($this->_formType) {
616 $this->assign('formType', $this->_formType);
617 return;
618 }
619
620 $this->applyFilter('__ALL__', 'trim');
621
622 if ($this->_action & CRM_Core_Action::DELETE) {
623 $this->addButtons(array(
624 array(
625 'type' => 'next',
626 'name' => ts('Delete'),
627 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
628 'isDefault' => TRUE,
629 ),
630 array(
631 'type' => 'cancel',
632 'name' => ts('Cancel'),
633 ),
634 )
635 );
636 return;
637 }
638
639 //need to assign custom data type and subtype to the template
640 $this->assign('customDataType', 'Contribution');
641 $this->assign('customDataSubType', $this->_contributionType);
642 $this->assign('entityID', $this->_id);
643
644 if ($this->_context == 'standalone') {
645 $this->addEntityRef('contact_id', ts('Contact'), array(
646 'create' => TRUE,
647 'api' => array('extra' => array('email')),
648 ), TRUE);
649 }
650
651 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
652
653 $financialType = $this->add('select', 'financial_type_id',
654 ts('Financial Type'),
655 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
656 TRUE,
657 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
658 );
659 $paymentInstrument = FALSE;
660 if (!$this->_mode) {
661 $paymentInstrument = $this->add('select', 'payment_instrument_id',
662 ts('Paid By'),
663 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
664 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
665 );
666 }
667
668 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
669
670 //add receipt for offline contribution
671 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
672
673 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
674
675 $status = CRM_Contribute_PseudoConstant::contributionStatus();
676
677 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
678 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
679 if ($this->_ppID) {
680 foreach (array(
681 'Cancelled',
682 'Failed',
683 'In Progress',
684 ) as $suppress) {
685 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
686 }
687 }
688 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
689 $suppressFlag = FALSE;
690 if ($this->_id) {
691 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
692 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
693 $suppressFlag = TRUE;
694 }
695 }
696 if (!$suppressFlag) {
697 foreach (array(
698 'Overdue',
699 'In Progress',
700 ) as $suppress) {
701 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
702 }
703 }
704 else {
705 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
706 }
707 }
708
709 if ($this->_id) {
710 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
711 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
712 switch ($name) {
713 case 'Completed':
714 case 'Cancelled':
715 case 'Refunded':
716 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
717 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
718 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
719 break;
720
721 case 'Pending':
722 case 'In Progress':
723 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
724 break;
725
726 case 'Failed':
727 foreach (array(
728 'Pending',
729 'Refunded',
730 'Completed',
731 'In Progress',
732 'Cancelled',
733 ) as $suppress) {
734 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
735 }
736 break;
737 }
738 }
739 else {
740 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
741 }
742
743 $this->add('select', 'contribution_status_id',
744 ts('Contribution Status'),
745 $status,
746 FALSE
747 );
748
749 // add various dates
750 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
751
752 if ($this->_online) {
753 $this->assign('hideCalender', TRUE);
754 }
755 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
756
757 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
758 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
759
760 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
761
762 $element = $this->add('select',
763 'payment_processor_id',
764 ts('Payment Processor'),
765 $this->_processors,
766 NULL,
767 $recurJs
768 );
769
770 if ($this->_online) {
771 $element->freeze();
772 }
773 $totalAmount = NULL;
774 if (empty($this->_lineItems)) {
775 $buildPriceSet = FALSE;
776 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
777 if (!empty($priceSets) && !$this->_ppID) {
778 $buildPriceSet = TRUE;
779 }
780
781 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
782 // and if we already have line items for that participant. CRM-5095
783 if ($buildPriceSet && $this->_id) {
784 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
785 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
786 $this->_id,
787 'id',
788 'contribution_id'
789 );
790 if ($pledgePaymentId) {
791 $buildPriceSet = FALSE;
792 }
793 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
794 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
795 if (!CRM_Utils_System::isNull($participantLI)) {
796 $buildPriceSet = FALSE;
797 }
798 }
799 }
800
801 $hasPriceSets = FALSE;
802 if ($buildPriceSet) {
803 $hasPriceSets = TRUE;
804 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
805 array(
806 '' => ts('Choose price set'),
807 ) + $priceSets,
808 NULL, array('onchange' => "buildAmount( this.value );")
809 );
810 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
811 $element->freeze();
812 }
813 }
814 $this->assign('hasPriceSets', $hasPriceSets);
815 $currencyFreeze = FALSE;
816 if (!($this->_action & CRM_Core_Action::UPDATE)) {
817 if ($this->_online || $this->_ppID) {
818 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
819 'READONLY' => TRUE,
820 'style' => "background-color:#EBECE4",
821 ));
822 $optionTypes = array(
823 '1' => ts('Adjust Pledge Payment Schedule?'),
824 '2' => ts('Adjust Total Pledge Amount?'),
825 );
826 $this->addRadio('option_type',
827 NULL,
828 $optionTypes,
829 array(), '<br/>'
830 );
831
832 $currencyFreeze = TRUE;
833 }
834 }
835
836 $totalAmount = $this->addMoney('total_amount',
837 ts('Total Amount'),
838 ($hasPriceSets) ? FALSE : TRUE,
839 $attributes['total_amount'],
840 TRUE, 'currency', NULL, $currencyFreeze
841 );
842 }
843
844 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
845
846 // CRM-7362 --add campaigns.
847 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
848
849 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
850
851 $js = NULL;
852 if (!$this->_mode) {
853 $js = array('onclick' => "return verify( );");
854 }
855
856 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
857 'mailing_backend'
858 );
859 $this->assign('outBound_option', $mailingInfo['outBound_option']);
860
861 $this->addButtons(array(
862 array(
863 'type' => 'upload',
864 'name' => ts('Save'),
865 'js' => $js,
866 'isDefault' => TRUE,
867 ),
868 array(
869 'type' => 'upload',
870 'name' => ts('Save and New'),
871 'js' => $js,
872 'subName' => 'new',
873 ),
874 array(
875 'type' => 'cancel',
876 'name' => ts('Cancel'),
877 ),
878 )
879 );
880
881 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
882 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
883 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
884 if ($totalAmount) {
885 $totalAmount->freeze();
886 }
887 $checkNumber->freeze();
888 $paymentInstrument->freeze();
889 $trxnId->freeze();
890 $financialType->freeze();
891 }
892
893 // if contribution is related to membership or participant freeze Financial Type, Amount
894 if ($this->_id && isset($this->_values['tax_amount'])) {
895 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
896 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
897 if ($totalAmount) {
898 $totalAmount->freeze();
899 }
900 $financialType->freeze();
901 $this->assign('freezeFinancialType', TRUE);
902 }
903 }
904
905 if ($this->_action & CRM_Core_Action::VIEW) {
906 $this->freeze();
907 }
908 }
909
910 /**
911 * Global form rule.
912 *
913 * @param array $fields
914 * The input form values.
915 * @param array $files
916 * The uploaded files if any.
917 * @param $self
918 *
919 * @return bool|array
920 * true if no errors, else array of errors
921 */
922 public static function formRule($fields, $files, $self) {
923 $errors = array();
924
925 // Check for Credit Card Contribution.
926 if ($self->_mode) {
927 if (empty($fields['payment_processor_id'])) {
928 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
929 }
930 else {
931 // validate payment instrument (e.g. credit card number)
932 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
933 }
934 }
935
936 // Do the amount validations.
937 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
938 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
939 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
940 }
941 }
942
943 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
944
945 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
946 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
947 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
948 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
949 }
950 }
951 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
952 if ($self->_id && $self->_values['contribution_status_id'] != $fields['contribution_status_id']) {
953 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
954 }
955 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
956 if ($self->_id && $self->_values['financial_type_id'] != $fields['financial_type_id']) {
957 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
958 }
959 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
960 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
961 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
962 }
963
964 // $trxn_id must be unique CRM-13919
965 if (!empty($fields['trxn_id'])) {
966 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
967 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
968 if ($self->_id) {
969 $queryParams[2] = array((int) $self->_id, 'Integer');
970 $query .= ' and id !=%2';
971 }
972 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
973 if ($tCnt) {
974 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
975 }
976 }
977
978 $errors = array_merge($errors, $softErrors);
979 return $errors;
980 }
981
982 /**
983 * Process the form submission.
984 */
985 public function postProcess() {
986 if ($this->_action & CRM_Core_Action::DELETE) {
987 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
988 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
989 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
990 ));
991 return;
992 }
993
994 // Get the submitted form values.
995 $submittedValues = $this->controller->exportValues($this->_name);
996 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
997 $session = CRM_Core_Session::singleton();
998 $buttonName = $this->controller->getButtonName();
999 if ($this->_context == 'standalone') {
1000 if ($buttonName == $this->getButtonName('upload', 'new')) {
1001 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1002 'reset=1&action=add&context=standalone'
1003 ));
1004 }
1005 else {
1006 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1007 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1008 ));
1009 }
1010 }
1011 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1012 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1013 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1014 ));
1015 }
1016 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1017 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1018 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1019 ));
1020 }
1021
1022 //store contribution ID if not yet set (on create)
1023 if (empty($this->_id) && !empty($contribution->id)) {
1024 $this->_id = $contribution->id;
1025 }
1026 }
1027
1028 /**
1029 * Process credit card payment.
1030 *
1031 * @param array $submittedValues
1032 * @param array $lineItem
1033 *
1034 * @return bool|\CRM_Contribute_DAO_Contribution
1035 */
1036 protected function processCreditCard($submittedValues, $lineItem) {
1037 $sendReceipt = $contribution = FALSE;
1038
1039 $unsetParams = array(
1040 'trxn_id',
1041 'payment_instrument_id',
1042 'contribution_status_id',
1043 'cancel_date',
1044 'cancel_reason',
1045 );
1046 foreach ($unsetParams as $key) {
1047 if (isset($submittedValues[$key])) {
1048 unset($submittedValues[$key]);
1049 }
1050 }
1051 $isTest = ($this->_mode == 'test') ? 1 : 0;
1052 // CRM-12680 set $_lineItem if its not set
1053 if (empty($this->_lineItem) && !empty($lineItem)) {
1054 $this->_lineItem = $lineItem;
1055 }
1056
1057 //Get the require fields value only.
1058 $params = $this->_params = $submittedValues;
1059
1060 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor_id'],
1061 $this->_mode
1062 );
1063
1064 // Get the payment processor id as per mode.
1065 $this->_params['payment_processor'] = $params['payment_processor_id']
1066 = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1067
1068 $now = date('YmdHis');
1069 $fields = array();
1070
1071 // we need to retrieve email address
1072 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1073 list($this->userDisplayName,
1074 $this->userEmail
1075 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1076 $this->assign('displayName', $this->userDisplayName);
1077 }
1078
1079 // Set email for primary location.
1080 $fields['email-Primary'] = 1;
1081 $params['email-Primary'] = $this->userEmail;
1082
1083 // now set the values for the billing location.
1084 foreach (array_keys($this->_fields) as $name) {
1085 $fields[$name] = 1;
1086 }
1087
1088 // also add location name to the array
1089 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
1090
1091 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1092 $fields["address_name-{$this->_bltID}"] = 1;
1093 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1094 $this->_contactID,
1095 'contact_type'
1096 );
1097
1098 $nameFields = array('first_name', 'middle_name', 'last_name');
1099 foreach ($nameFields as $name) {
1100 $fields[$name] = 1;
1101 if (array_key_exists("billing_$name", $params)) {
1102 $params[$name] = $params["billing_{$name}"];
1103 $params['preserveDBName'] = TRUE;
1104 }
1105 }
1106
1107 if (!empty($params['source'])) {
1108 unset($params['source']);
1109 }
1110 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1111 $this->_contactID,
1112 NULL, NULL,
1113 $ctype
1114 );
1115
1116 // add all the additional payment params we need
1117 if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
1118 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
1119 }
1120 if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
1121 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1122 }
1123 $legacyCreditCardExpiryCheck = FALSE;
1124 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
1125 $legacyCreditCardExpiryCheck = TRUE;
1126 }
1127 if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
1128 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1129 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1130 }
1131 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1132 $this->_params['amount'] = $this->_params['total_amount'];
1133 $this->_params['amount_level'] = 0;
1134 $this->_params['description'] = ts('Office Credit Card contribution');
1135 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1136 $this->_params,
1137 CRM_Core_Config::singleton()->defaultCurrency
1138 );
1139 $this->_params['payment_action'] = 'Sale';
1140 if (!empty($this->_params['receive_date'])) {
1141 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1142 }
1143
1144 if (!empty($params['soft_credit_to'])) {
1145 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1146 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1147 }
1148
1149 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1150 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1151 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1152
1153 //Add common data to formatted params
1154 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1155
1156 if (empty($this->_params['invoice_id'])) {
1157 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1158 }
1159 else {
1160 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1161 }
1162
1163 // At this point we've created a contact and stored its address etc
1164 // all the payment processors expect the name and address to be in the
1165 // so we copy stuff over to first_name etc.
1166 $paymentParams = $this->_params;
1167 $paymentParams['contactID'] = $this->_contactID;
1168 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1169
1170 $financialType = new CRM_Financial_DAO_FinancialType();
1171 $financialType->id = $params['financial_type_id'];
1172
1173 // Add some financial type details to the params list
1174 // if folks need to use it.
1175 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
1176 $paymentParams['contributionPageID'] = NULL;
1177
1178 if (!empty($this->_params['is_email_receipt'])) {
1179 $paymentParams['email'] = $this->userEmail;
1180 $paymentParams['is_email_receipt'] = 1;
1181 }
1182 else {
1183 $paymentParams['is_email_receipt'] = 0;
1184 $this->_params['is_email_receipt'] = 0;
1185 }
1186 if (!empty($this->_params['receive_date'])) {
1187 $paymentParams['receive_date'] = $this->_params['receive_date'];
1188 }
1189
1190 // For recurring contribution, create Contribution Record first.
1191 // Contribution ID, Recurring ID and Contact ID needed
1192 // When we get a callback from the payment processor, CRM-7115
1193
1194 if (!empty($paymentParams['is_recur'])) {
1195 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1196 $this->_params,
1197 NULL,
1198 $this->_contactID,
1199 $financialType,
1200 TRUE,
1201 FALSE,
1202 $isTest,
1203 $this->_lineItem
1204 );
1205 $paymentParams['contributionID'] = $contribution->id;
1206 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1207 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1208 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1209 }
1210 $result = array();
1211 if ($paymentParams['amount'] > 0.0) {
1212 // force a re-get of the payment processor in case the form changed it, CRM-7179
1213 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1214 try {
1215 $result = $payment->doPayment($paymentParams, 'contribute');
1216 }
1217 catch (CRM_Core_Exception $e) {
1218 $message = ts("Payment Processor Error message") . $e->getMessage();
1219 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1220 // Set the contribution mode.
1221 $urlParams = "action=add&cid={$this->_contactID}";
1222 if ($this->_mode) {
1223 $urlParams .= "&mode={$this->_mode}";
1224 }
1225 if (!empty($this->_ppID)) {
1226 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1227 }
1228 CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1229 }
1230 }
1231
1232 $this->_params = array_merge($this->_params, $result);
1233
1234 $this->_params['receive_date'] = $now;
1235
1236 if (!empty($this->_params['is_email_receipt'])) {
1237 $this->_params['receipt_date'] = $now;
1238 }
1239 else {
1240 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1241 $params['receipt_date_time'], TRUE
1242 );
1243 }
1244
1245 $this->set('params', $this->_params);
1246 $this->assign('trxn_id', $result['trxn_id']);
1247 $this->assign('receive_date', $this->_params['receive_date']);
1248
1249 // Result has all the stuff we need
1250 // lets archive it to a financial transaction
1251 if ($financialType->is_deductible) {
1252 $this->assign('is_deductible', TRUE);
1253 $this->set('is_deductible', TRUE);
1254 }
1255
1256 // Set source if not set
1257 if (empty($this->_params['source'])) {
1258 $userID = CRM_Core_Session::singleton()->get('userID');
1259 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1260 'sort_name'
1261 );
1262 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1263 }
1264
1265 // Build custom data getFields array
1266 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1267 CRM_Utils_Array::value('financial_type_id', $params)
1268 );
1269 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1270 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1271 );
1272 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1273 $customFields,
1274 $this->_id,
1275 'Contribution'
1276 );
1277 if (empty($paymentParams['is_recur'])) {
1278 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1279 $this->_params,
1280 $result,
1281 $this->_contactID,
1282 $financialType,
1283 FALSE, FALSE,
1284 $isTest,
1285 $this->_lineItem
1286 );
1287 }
1288
1289 // Send receipt mail.
1290 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1291 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1292 $this->_params['contact_id'] = $this->_contactID;
1293 $this->_params['contribution_id'] = $contribution->id;
1294 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1295 }
1296
1297 if ($contribution->id) {
1298 array_unshift($this->statusMessage, ts('The contribution record has been processed.'));
1299 if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
1300 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1301 }
1302 $this->statusMessageTitle = ts('Complete');
1303 }
1304 return $contribution;
1305 }
1306
1307 /**
1308 * Clean up DB after payment fails.
1309 *
1310 * This function removes related DB entries. Note that it has been agreed in principle,
1311 * but not implemented, that contributions should be retained as 'Failed' rather than
1312 * deleted.
1313 *
1314 * @todo it doesn't clean up line items.
1315 *
1316 * @param array $paymentParams
1317 * @param string $message
1318 */
1319 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1320 // Make sure to cleanup db for recurring case.
1321 if (!empty($paymentParams['contributionID'])) {
1322 CRM_Core_Error::debug_log_message($message .
1323 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1324 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1325 }
1326 if (!empty($paymentParams['contributionRecurID'])) {
1327 CRM_Core_Error::debug_log_message($message .
1328 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1329 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1330 }
1331 }
1332
1333 /**
1334 * Generate the data to construct a snippet based pane.
1335 *
1336 * This form also assigns the showAdditionalInfo var based on historical code.
1337 * This appears to mean 'there is a pane to show'.
1338 *
1339 * @param string $type
1340 * Type of Pane - this is generally used to determine the function name used to build it
1341 * - e.g CreditCard, AdditionalDetail
1342 * @param array $defaults
1343 *
1344 * @return array
1345 * We aim to further refactor & simplify this but currently
1346 * - the panes array
1347 * - should additional info be shown?
1348 */
1349 protected function generatePane($type, $defaults) {
1350 $urlParams = "snippet=4&formType={$type}";
1351 if ($this->_mode) {
1352 $urlParams .= "&mode={$this->_mode}";
1353 }
1354
1355 $open = 'false';
1356 if ($type == 'CreditCard' ||
1357 $type == 'DirectDebit'
1358 ) {
1359 $open = 'true';
1360 }
1361
1362 $pane = array(
1363 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1364 'open' => $open,
1365 'id' => $type,
1366 );
1367
1368 // See if we need to include this paneName in the current form.
1369 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1370 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1371 ) {
1372 $this->assign('showAdditionalInfo', TRUE);
1373 $pane['open'] = 'true';
1374 }
1375
1376 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1377 // @todo would be good to align tpl name with form name...
1378 // @todo document why this hidden variable is required.
1379 $this->add('hidden', 'hidden_' . $type, 1);
1380 return $pane;
1381 }
1382 else {
1383 $additionalInfoFormFunction = 'build' . $type;
1384 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1385 return $pane;
1386 }
1387 }
1388
1389 /**
1390 * Wrapper for unit testing the post process submit function.
1391 *
1392 * (If we expose through api we can get default additions 'for free').
1393 *
1394 * @param array $params
1395 * @param int $action
1396 * @param string|null $creditCardMode
1397 *
1398 * @throws \CiviCRM_API3_Exception
1399 */
1400 public function testSubmit($params, $action, $creditCardMode = NULL) {
1401 $defaults = array(
1402 'soft_credit_contact_id' => array(),
1403 'receipt_date' => '',
1404 'receipt_date_time' => '',
1405 'cancel_date' => '',
1406 'cancel_date_time' => '',
1407 'hidden_Premium' => 1,
1408 );
1409 if (!empty($params['id'])) {
1410 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1411 'id' => $params['id'],
1412 ));
1413 }
1414 else {
1415 $existingContribution = array();
1416 }
1417
1418 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1419 $existingContribution
1420 );
1421
1422 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1423 $existingContribution
1424 );
1425
1426 if ($creditCardMode) {
1427 $this->_mode = $creditCardMode;
1428 }
1429
1430 // Required because processCreditCard calls set method on this.
1431 $_SERVER['REQUEST_METHOD'] = 'GET';
1432 $this->controller = new CRM_Core_Controller();
1433
1434 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1435
1436 $this->_fields = array();
1437 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1438
1439 }
1440
1441 /**
1442 * @param array $submittedValues
1443 *
1444 * @param int $action
1445 * Action constant
1446 * - CRM_Core_Action::UPDATE
1447 *
1448 * @param $pledgePaymentID
1449 *
1450 * @return array
1451 * @throws \Exception
1452 */
1453 protected function submit($submittedValues, $action, $pledgePaymentID) {
1454 $softParams = $softIDs = array();
1455 $pId = $contribution = $isRelatedId = FALSE;
1456
1457 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1458 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1459 $lineID = key($line);
1460 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1461 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1462 if ($quickConfig) {
1463 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1464 }
1465 }
1466
1467 // Process price set and get total amount and line items.
1468 $lineItem = array();
1469 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1470 if (empty($priceSetId) && !$this->_id) {
1471 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1472 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1473 $fieldID = key($this->_priceSet['fields']);
1474 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1475 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1476 $submittedValues['price_' . $fieldID] = 1;
1477 }
1478
1479 if ($priceSetId) {
1480 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1481 $submittedValues, $lineItem[$priceSetId]);
1482
1483 // Unset tax amount for offline 'is_quick_config' contribution.
1484 if ($this->_priceSet['is_quick_config'] &&
1485 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1486 ) {
1487 unset($submittedValues['tax_amount']);
1488 }
1489 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1490 }
1491 if ($this->_id) {
1492 if ($this->_compId) {
1493 if ($this->_context == 'participant') {
1494 $pId = $this->_compId;
1495 }
1496 elseif ($this->_context == 'membership') {
1497 $isRelatedId = TRUE;
1498 }
1499 else {
1500 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1501 }
1502 }
1503 else {
1504 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1505 if (array_key_exists('membership', $contributionDetails)) {
1506 $isRelatedId = TRUE;
1507 }
1508 elseif (array_key_exists('participant', $contributionDetails)) {
1509 $pId = $contributionDetails['participant'];
1510 }
1511 }
1512 }
1513 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1514 // CRM-10117 update the line items for participants.
1515 if ($pId) {
1516 $entityTable = 'participant';
1517 $entityID = $pId;
1518 $isRelatedId = FALSE;
1519 $participantParams = array(
1520 'fee_amount' => $submittedValues['total_amount'],
1521 'id' => $entityID,
1522 );
1523 CRM_Event_BAO_Participant::add($participantParams);
1524 if (empty($this->_lineItems)) {
1525 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1526 }
1527 }
1528 else {
1529 $entityTable = 'contribution';
1530 $entityID = $this->_id;
1531 }
1532
1533 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1534 foreach (array_keys($lineItems) as $id) {
1535 $lineItems[$id]['id'] = $id;
1536 }
1537 $itemId = key($lineItems);
1538 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1539 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1540 }
1541
1542 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1543 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1544
1545 // Update line total and total amount with tax on edit.
1546 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1547 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1548 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1549 }
1550 else {
1551 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1552 $submittedValues['tax_amount'] = 'null';
1553 }
1554 if ($lineItems[$itemId]['tax_rate']) {
1555 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1556 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1557 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1558 }
1559 }
1560 // CRM-10117 update the line items for participants.
1561 if (!empty($lineItems[$itemId]['price_field_id'])) {
1562 $lineItem[$this->_priceSetId] = $lineItems;
1563 }
1564 }
1565
1566 $isQuickConfig = 0;
1567 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1568 $isQuickConfig = 1;
1569 }
1570 //CRM-11529 for quick config back office transactions
1571 //when financial_type_id is passed in form, update the
1572 //line items with the financial type selected in form
1573 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1574 ) {
1575 foreach ($lineItem[$this->_priceSetId] as &$values) {
1576 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1577 }
1578 }
1579
1580 if (!isset($submittedValues['total_amount'])) {
1581 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1582 }
1583 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1584
1585 if (!empty($submittedValues['pcp_made_through_id'])) {
1586 $pcp = array();
1587 $fields = array(
1588 'pcp_made_through_id',
1589 'pcp_display_in_roll',
1590 'pcp_roll_nickname',
1591 'pcp_personal_note',
1592 );
1593 foreach ($fields as $f) {
1594 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1595 }
1596 }
1597
1598 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1599 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1600 //Delete existing soft credit records if soft credit list is empty on update
1601 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id));
1602 }
1603 else {
1604 //build soft credit params
1605 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1606 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1607 $softParams[$key]['contact_id'] = $val;
1608 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1609 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1610 if (!empty($submittedValues['soft_credit_id'][$key])) {
1611 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1612 }
1613 }
1614 }
1615 }
1616
1617 // set the contact, when contact is selected
1618 if (!empty($submittedValues['contact_id'])) {
1619 $this->_contactID = $submittedValues['contact_id'];
1620 }
1621 $formValues = $submittedValues;
1622
1623 // Credit Card Contribution.
1624 if ($this->_mode) {
1625 $contribution = $this->processCreditCard($submittedValues, $lineItem);
1626 }
1627 else {
1628 // Offline Contribution.
1629 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1630
1631 // get the required field value only.
1632
1633 $params = $ids = array();
1634
1635 $params['contact_id'] = $this->_contactID;
1636 $params['currency'] = $this->getCurrency($submittedValues);
1637
1638 $fields = array(
1639 'financial_type_id',
1640 'contribution_status_id',
1641 'payment_instrument_id',
1642 'cancel_reason',
1643 'source',
1644 'check_number',
1645 );
1646 foreach ($fields as $f) {
1647 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1648 }
1649
1650 if (!empty($pcp)) {
1651 $params['pcp'] = $pcp;
1652 }
1653 if (!empty($softParams)) {
1654 $params['soft_credit'] = $softParams;
1655 $params['soft_credit_ids'] = $softIDs;
1656 }
1657
1658 // CRM-5740 if priceset is used, no need to cleanup money.
1659 if ($priceSetId) {
1660 $params['skipCleanMoney'] = 1;
1661 }
1662
1663 $dates = array(
1664 'receive_date',
1665 'receipt_date',
1666 'cancel_date',
1667 );
1668
1669 foreach ($dates as $d) {
1670 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1671 }
1672
1673 if (!empty($formValues['is_email_receipt'])) {
1674 $params['receipt_date'] = date("Y-m-d");
1675 }
1676
1677 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1678 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1679 ) {
1680 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1681 $params['cancel_date'] = date('Y-m-d');
1682 }
1683 }
1684 else {
1685 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1686 }
1687
1688 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1689 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1690 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1691 $params['is_pay_later'] = 1;
1692 }
1693 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1694 $params['is_pay_later'] = 0;
1695 }
1696
1697 $ids['contribution'] = $params['id'] = $this->_id;
1698
1699 // Add Additional common information to formatted params.
1700 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1701 if ($pId) {
1702 $params['contribution_mode'] = 'participant';
1703 $params['participant_id'] = $pId;
1704 $params['skipLineItem'] = 1;
1705 }
1706 elseif ($isRelatedId) {
1707 $params['contribution_mode'] = 'membership';
1708 }
1709 $params['line_item'] = $lineItem;
1710 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1711 if (isset($submittedValues['tax_amount'])) {
1712 $params['tax_amount'] = $submittedValues['tax_amount'];
1713 }
1714 //create contribution.
1715 if ($isQuickConfig) {
1716 $params['is_quick_config'] = 1;
1717 }
1718 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1719
1720 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1721
1722 // process associated membership / participant, CRM-4395
1723 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1724 $this->statusMessage[] = $this->updateRelatedComponent($contribution->id,
1725 $contribution->contribution_status_id,
1726 CRM_Utils_Array::value('contribution_status_id',
1727 $this->_values
1728 ),
1729 $contribution->receive_date
1730 );
1731 }
1732
1733 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1734
1735 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1736
1737 //send receipt mail.
1738 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1739 $formValues['contact_id'] = $this->_contactID;
1740 $formValues['contribution_id'] = $contribution->id;
1741
1742 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1743
1744 // to get 'from email id' for send receipt
1745 $this->fromEmailId = $formValues['from_email_address'];
1746 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1747 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1748 }
1749 }
1750
1751 $this->statusMessageTitle = ts('Saved');
1752
1753 }
1754
1755 if ($contribution->id && isset($formValues['product_name'][0])) {
1756 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1757 $this->_premiumID, $this->_options
1758 );
1759 }
1760
1761 if ($contribution->id && isset($submittedValues['note'])) {
1762 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1763 }
1764
1765 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1766
1767 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1768 $action,
1769 $pledgePaymentID,
1770 $contribution->id,
1771 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1772 $formValues['total_amount'],
1773 CRM_Utils_Array::value('total_amount', $this->_defaults),
1774 $formValues['contribution_status_id'],
1775 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1776 );
1777 return $contribution;
1778 }
1779
1780 /**
1781 * Assign tax calculations to contribution receipts.
1782 *
1783 * @param array $submittedValues
1784 * @param int $action
1785 * @param array $lineItem
1786 */
1787 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1788
1789 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1790 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1791 return;
1792 }
1793 $taxRate = array();
1794 $getTaxDetails = FALSE;
1795 if ($action & CRM_Core_Action::ADD) {
1796 $line = $lineItem;
1797 }
1798 elseif ($action & CRM_Core_Action::UPDATE) {
1799 $line = $this->_lineItems;
1800 }
1801 foreach ($line as $key => $value) {
1802 foreach ($value as $v) {
1803 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1804 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1805 }
1806 else {
1807 if (isset($v['tax_rate'])) {
1808 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1809 $getTaxDetails = TRUE;
1810 }
1811 }
1812 }
1813 }
1814
1815 if ($action & CRM_Core_Action::UPDATE) {
1816 if (isset($submittedValues['tax_amount'])) {
1817 $totalTaxAmount = $submittedValues['tax_amount'];
1818 }
1819 else {
1820 $totalTaxAmount = $this->_values['tax_amount'];
1821 }
1822 $this->assign('totalTaxAmount', $totalTaxAmount);
1823 $this->assign('dataArray', $taxRate);
1824 }
1825 else {
1826 if (!empty($submittedValues['price_set_id'])) {
1827 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1828 $this->assign('getTaxDetails', $getTaxDetails);
1829 $this->assign('dataArray', $taxRate);
1830 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1831 }
1832 else {
1833 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1834 }
1835 }
1836 }
1837
1838 /**
1839 * Calculate non deductible amount.
1840 *
1841 * CRM-11956
1842 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1843 * if non_deductible_amount does NOT exist - then calculate it depending on:
1844 * $financialType->is_deductible and whether there is a product (premium).
1845 *
1846 * @param $params
1847 * @param $formValues
1848 *
1849 * @return array
1850 */
1851 protected function calculateNonDeductibleAmount($params, $formValues) {
1852 if (!empty($params['non_deductible_amount'])) {
1853 return $params['non_deductible_amount'];
1854 }
1855 if (empty($params['non_deductible_amount'])) {
1856 $contributionType = new CRM_Financial_DAO_FinancialType();
1857 $contributionType->id = $params['financial_type_id'];
1858
1859 if ($contributionType->is_deductible) {
1860
1861 if (isset($formValues['product_name'][0])) {
1862 $selectProduct = $formValues['product_name'][0];
1863 }
1864 // if there is a product - compare the value to the contribution amount
1865 if (isset($selectProduct)) {
1866 $productDAO = new CRM_Contribute_DAO_Product();
1867 $productDAO->id = $selectProduct;
1868 $productDAO->find(TRUE);
1869 // product value exceeds contribution amount
1870 if ($params['total_amount'] < $productDAO->price) {
1871 return $params['total_amount'];
1872 }
1873 // product value does NOT exceed contribution amount
1874 else {
1875 return $productDAO->price;
1876 }
1877 }
1878 // contribution is deductible - but there is no product
1879 else {
1880 return '0.00';
1881 }
1882 }
1883 // contribution is NOT deductible
1884 else {
1885 return $params['total_amount'];
1886 }
1887 }
1888 return 0;
1889 }
1890
1891 }