3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This class generates form components for processing a contribution.
31 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
33 * The id of the contribution that we are processing.
40 * The id of the premium that we are processing.
44 public $_premiumID = NULL;
47 * @var CRM_Contribute_DAO_ContributionProduct
49 public $_productDAO = NULL;
59 * The id of the contact associated with this contribution.
66 * The id of the pledge payment that we are processing.
73 * The id of the pledge that we are processing.
80 * Is this contribution associated with an online.
81 * financial transaction
85 public $_online = FALSE;
88 * Stores all product options.
95 * Storage of parameters from form
102 * Store the contribution Type ID
106 public $_contributionType;
109 * The contribution values if an existing contribution
114 * The pledge values if this contribution is associated with pledge
116 public $_pledgeValues;
118 public $_contributeMode = 'direct';
123 * Parameter with confusing name.
127 public $_compContext;
132 * Possible From email addresses
144 * Store the line items if price set used.
150 * @todo explain why we use lineItem & lineItems
156 * @var array soft credit info
158 public $_softCreditInfo;
160 protected $_formType;
163 * @todo what on earth does cdType stand for????
167 public $_honoreeProfileType;
170 * Array of billing panes to be displayed by billingBlock.tpl.
171 * Currently this is likely to look like
172 * array('Credit Card' => ts('Credit Card') or
173 * array('Direct Debit => ts('Direct Debit')
174 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
178 public $billingPane = array();
181 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
182 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
186 public $_paymentFields = array();
188 * Logged in user's email.
201 * Price set as an array
208 * @todo can we define this a as protected? can we define higher up the chain
218 public $userDisplayName;
221 * Set variables up before form is built.
223 public function preProcess() {
225 // Check permission for action.
226 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
227 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
230 // @todo - if anyone ever figures out what this _cdType subroutine is about
231 // (or even if it still applies) please add comments!!!!!!!!!!
232 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
233 $this->assign('cdType', FALSE);
234 if ($this->_cdType
) {
235 $this->assign('cdType', TRUE);
236 CRM_Custom_Form_CustomData
::preProcess($this);
240 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
243 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId
);
245 $this->assign('priceSetId', $this->_priceSetId
);
247 // Get the pledge payment id
248 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
250 // Get the contact id
251 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
254 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
255 $this->assign('action', $this->_action
);
257 // Get the contribution id if update
258 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
259 if (!empty($this->_id
)) {
260 $this->assign('contribID', $this->_id
);
263 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
264 $this->assign('context', $this->_context
);
266 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
268 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
270 //set the contribution mode.
271 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
273 $this->assign('contributionMode', $this->_mode
);
274 if ($this->_action
& CRM_Core_Action
::DELETE
) {
278 $this->assign('showCheckNumber', TRUE);
280 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
281 $this->assignPaymentRelatedVariables();
283 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
284 $this->preProcessPledge();
288 $this->showRecordLinkMesssage($this->_id
);
290 $this->_values
= array();
292 // Current contribution id.
294 $this->assignPremiumProduct($this->_id
);
295 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
298 // when custom data is included in this page
299 if (!empty($_POST['hidden_custom'])) {
300 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
303 $this->_lineItems
= array();
305 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
306 $this->assign('compId', $this->_compId
);
307 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
310 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
312 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
315 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
319 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
322 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
326 CRM_Contribute_Form_SoftCredit
::preprocess($this);
331 * Set default values.
335 public function setDefaultValues() {
336 if ($this->_cdType
) {
337 // @todo document when this function would be called in this way
338 // (and whether it is valid or an overloading of this form).
339 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
342 $defaults = $this->_values
;
344 // Set defaults for pledge payment.
346 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
347 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
348 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
349 $defaults['option_type'] = 1;
352 if ($this->_action
& CRM_Core_Action
::DELETE
) {
356 $defaults['frequency_interval'] = 1;
357 $defaults['frequency_unit'] = 'month';
359 // Set soft credit defaults.
360 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
363 $config = CRM_Core_Config
::singleton();
364 // Set default country from config if no country set.
365 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
366 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
369 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
370 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
373 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
374 $defaults = array_merge($defaults, $billingDefaults);
378 $this->_contactID
= $defaults['contact_id'];
381 // Set $newCredit variable in template to control whether link to credit card mode is included.
382 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
384 // Fix the display of the monetary value, CRM-4038.
385 if (isset($defaults['total_amount'])) {
386 if (!empty($defaults['tax_amount'])) {
387 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
388 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
389 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
393 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
397 if (isset($defaults['non_deductible_amount'])) {
398 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
401 if (isset($defaults['fee_amount'])) {
402 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
405 if (isset($defaults['net_amount'])) {
406 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
409 if ($this->_contributionType
) {
410 $defaults['financial_type_id'] = $this->_contributionType
;
413 if (empty($defaults['payment_instrument_id'])) {
414 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
417 if (!empty($defaults['is_test'])) {
418 $this->assign('is_test', TRUE);
421 $this->assign('showOption', TRUE);
422 // For Premium section.
423 if ($this->_premiumID
) {
424 $this->assign('showOption', FALSE);
425 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
427 $this->assign('showOption', TRUE);
429 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
431 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
434 $defaults['product_name'] = array($this->_productDAO
->product_id
);
436 if ($this->_productDAO
->fulfilled_date
) {
437 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
441 if (isset($this->userEmail
)) {
442 $this->assign('email', $this->userEmail
);
445 if (!empty($defaults['is_pay_later'])) {
446 $this->assign('is_pay_later', TRUE);
448 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
456 foreach ($dates as $key) {
457 if (!empty($defaults[$key])) {
458 list($defaults[$key], $defaults[$key . '_time'])
459 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
463 if (!$this->_id
&& empty($defaults['receive_date'])) {
464 list($defaults['receive_date'],
465 $defaults['receive_date_time']
466 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
469 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
470 CRM_Utils_Array
::value('receive_date_time', $defaults)
472 $currency = CRM_Utils_Array
::value('currency', $defaults);
473 $this->assign('currency', $currency);
474 // Hack to get currency info to the js layer. CRM-11440.
475 CRM_Utils_Money
::format(1);
476 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
477 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
479 // Inherit campaign from pledge.
480 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
481 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
484 $this->_defaults
= $defaults;
489 * Build the form object.
491 public function buildQuickForm() {
492 //@todo document the purpose of cdType (if still in use)
493 if ($this->_cdType
) {
494 CRM_Custom_Form_CustomData
::buildQuickForm($this);
498 //tax rate from financialType
499 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
500 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
502 // build price set form.
503 $buildPriceSet = FALSE;
504 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
505 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
506 $this->assign('invoicing', $invoicing);
508 // display tax amount on edit contribution page
509 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
510 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
513 if (empty($this->_lineItems
) &&
514 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
516 $buildPriceSet = TRUE;
517 $getOnlyPriceSetElements = TRUE;
518 if (!$this->_priceSetId
) {
519 $this->_priceSetId
= $_POST['price_set_id'];
520 $getOnlyPriceSetElements = FALSE;
523 $this->set('priceSetId', $this->_priceSetId
);
524 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
526 // get only price set form elements.
527 if ($getOnlyPriceSetElements) {
531 // use to build form during form rule.
532 $this->assign('buildPriceSet', $buildPriceSet);
534 $showAdditionalInfo = FALSE;
536 $defaults = $this->_values
;
537 $additionalDetailFields = array(
541 'non_deductible_amount',
545 foreach ($additionalDetailFields as $key) {
546 if (!empty($defaults[$key])) {
547 $defaults['hidden_AdditionalDetail'] = 1;
552 if ($this->_productDAO
) {
553 if ($this->_productDAO
->product_id
) {
554 $defaults['hidden_Premium'] = 1;
558 if ($this->_noteID
&&
559 isset($this->_values
['note'])
561 $defaults['hidden_AdditionalDetail'] = 1;
565 ts('Additional Details') => 'AdditionalDetail',
568 //Add Premium pane only if Premium is exists.
569 $dao = new CRM_Contribute_DAO_Product();
572 if ($dao->find(TRUE)) {
573 $paneNames[ts('Premium Information')] = 'Premium';
576 $billingPanes = array();
578 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
579 $buildRecurBlock = TRUE;
580 foreach ($this->billingPane
as $name => $label) {
581 if (!empty($this->billingFieldSets
[$name]['fields'])) {
582 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
583 $billingPanes[$label] = $this->generatePane(CRM_Utils_String
::convertStringToCamel($name), $defaults);
589 foreach ($paneNames as $name => $type) {
590 $allPanes[$name] = $this->generatePane($type, $defaults);
592 if (empty($this->_recurPaymentProcessors
)) {
593 $buildRecurBlock = FALSE;
595 if ($buildRecurBlock) {
596 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
597 $this->setDefaults(array('is_recur' => 0));
599 $this->assign('buildRecurBlock', $buildRecurBlock);
600 $qfKey = $this->controller
->_key
;
601 $this->assign('qfKey', $qfKey);
602 $this->assign('billingPanes', $billingPanes);
603 $this->assign('allPanes', $allPanes);
605 if ($this->_formType
) {
606 $this->assign('formType', $this->_formType
);
610 $this->applyFilter('__ALL__', 'trim');
612 if ($this->_action
& CRM_Core_Action
::DELETE
) {
613 $this->addButtons(array(
616 'name' => ts('Delete'),
617 'spacing' => ' ',
622 'name' => ts('Cancel'),
629 //need to assign custom data type and subtype to the template
630 $this->assign('customDataType', 'Contribution');
631 $this->assign('customDataSubType', $this->_contributionType
);
632 $this->assign('entityID', $this->_id
);
634 if ($this->_context
== 'standalone') {
635 $this->addEntityRef('contact_id', ts('Contact'), array(
637 'api' => array('extra' => array('email')),
641 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
643 $financialType = $this->add('select', 'financial_type_id',
644 ts('Financial Type'),
645 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
647 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
649 $paymentInstrument = FALSE;
651 $paymentInstrument = $this->add('select', 'payment_instrument_id',
653 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
654 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
658 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
660 //add receipt for offline contribution
661 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
663 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
665 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
667 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
668 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
675 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
678 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
679 $suppressFlag = FALSE;
681 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
682 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
683 $suppressFlag = TRUE;
686 if (!$suppressFlag) {
691 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
695 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
700 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
701 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
706 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
707 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
708 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
713 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
724 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
730 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
733 $this->add('select', 'contribution_status_id',
734 ts('Contribution Status'),
740 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
742 if ($this->_online
) {
743 $this->assign('hideCalender', TRUE);
745 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
747 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
748 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
750 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
753 if ($buildRecurBlock) {
754 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
756 $element = $this->add('select',
757 'payment_processor_id',
758 ts('Payment Processor'),
764 if ($this->_online
) {
768 if (empty($this->_lineItems
)) {
769 $buildPriceSet = FALSE;
770 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
771 if (!empty($priceSets) && !$this->_ppID
) {
772 $buildPriceSet = TRUE;
775 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
776 // and if we already have line items for that participant. CRM-5095
777 if ($buildPriceSet && $this->_id
) {
778 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
779 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
784 if ($pledgePaymentId) {
785 $buildPriceSet = FALSE;
787 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
788 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
789 if (!CRM_Utils_System
::isNull($participantLI)) {
790 $buildPriceSet = FALSE;
795 $hasPriceSets = FALSE;
796 if ($buildPriceSet) {
797 $hasPriceSets = TRUE;
798 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
800 '' => ts('Choose price set'),
802 NULL, array('onchange' => "buildAmount( this.value );")
804 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
808 $this->assign('hasPriceSets', $hasPriceSets);
809 $currencyFreeze = FALSE;
810 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
811 if ($this->_online ||
$this->_ppID
) {
812 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
814 'style' => "background-color:#EBECE4",
816 $optionTypes = array(
817 '1' => ts('Adjust Pledge Payment Schedule?'),
818 '2' => ts('Adjust Total Pledge Amount?'),
820 $this->addRadio('option_type',
826 $currencyFreeze = TRUE;
830 $totalAmount = $this->addMoney('total_amount',
832 ($hasPriceSets) ?
FALSE : TRUE,
833 $attributes['total_amount'],
834 TRUE, 'currency', NULL, $currencyFreeze
838 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
840 // CRM-7362 --add campaigns.
841 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
843 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
847 $js = array('onclick' => "return verify( );");
850 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
853 $this->assign('outBound_option', $mailingInfo['outBound_option']);
855 $this->addButtons(array(
858 'name' => ts('Save'),
864 'name' => ts('Save and New'),
870 'name' => ts('Cancel'),
875 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
876 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
877 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
879 $totalAmount->freeze();
881 $checkNumber->freeze();
882 $paymentInstrument->freeze();
884 $financialType->freeze();
887 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
889 // if contribution is related to membership or participant freeze Financial Type, Amount
890 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
891 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
892 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
894 $totalAmount->freeze();
896 $financialType->freeze();
897 $this->assign('freezeFinancialType', TRUE);
901 if ($this->_action
& CRM_Core_Action
::VIEW
) {
909 * @param array $fields
910 * The input form values.
911 * @param array $files
912 * The uploaded files if any.
916 * true if no errors, else array of errors
918 public static function formRule($fields, $files, $self) {
921 // Check for Credit Card Contribution.
923 if (empty($fields['payment_processor_id'])) {
924 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
928 // Do the amount validations.
929 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
930 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
931 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
935 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
937 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
938 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
939 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
940 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
943 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
944 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
945 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
948 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
949 if (!empty($fields['fee_amount']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
950 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
953 // $trxn_id must be unique CRM-13919
954 if (!empty($fields['trxn_id'])) {
955 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
956 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
958 $queryParams[2] = array((int) $self->_id
, 'Integer');
959 $query .= ' and id !=%2';
961 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
963 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
967 $errors = array_merge($errors, $softErrors);
972 * Process the form submission.
974 public function postProcess() {
975 $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
976 $softParams = $softIDs = array();
978 if ($this->_action
& CRM_Core_Action
::DELETE
) {
979 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
980 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
981 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
986 // Get the submitted form values.
987 $submittedValues = $this->controller
->exportValues($this->_name
);
988 if (!empty($submittedValues['price_set_id']) && $this->_action
& CRM_Core_Action
::UPDATE
) {
989 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
990 $lineID = key($line);
991 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
992 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
994 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
998 // Process price set and get total amount and line items.
1000 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1001 if (empty($priceSetId) && !$this->_id
) {
1002 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1003 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1004 $fieldID = key($this->_priceSet
['fields']);
1005 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1006 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1007 $submittedValues['price_' . $fieldID] = 1;
1011 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1012 $submittedValues, $lineItem[$priceSetId]);
1014 // Unset tax amount for offline 'is_quick_config' contribution.
1015 if ($this->_priceSet
['is_quick_config'] &&
1016 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1018 unset($submittedValues['tax_amount']);
1020 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1023 if ($this->_compId
) {
1024 if ($this->_context
== 'participant') {
1025 $pId = $this->_compId
;
1027 elseif ($this->_context
== 'membership') {
1028 $isRelatedId = TRUE;
1031 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1035 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1036 if (array_key_exists('membership', $contributionDetails)) {
1037 $isRelatedId = TRUE;
1039 elseif (array_key_exists('participant', $contributionDetails)) {
1040 $pId = current($contributionDetails['participant']);
1046 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1050 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1051 // CRM-10117 update the line items for participants.
1053 $entityTable = 'participant';
1055 $isRelatedId = FALSE;
1056 $participantParams = array(
1057 'fee_amount' => $submittedValues['total_amount'],
1060 CRM_Event_BAO_Participant
::add($participantParams);
1061 if (empty($this->_lineItems
)) {
1062 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1066 $entityTable = 'contribution';
1067 $entityID = $this->_id
;
1070 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, $isQuickConfig, $isRelatedId);
1071 foreach (array_keys($lineItems) as $id) {
1072 $lineItems[$id]['id'] = $id;
1074 $itemId = key($lineItems);
1075 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1076 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1079 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1080 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1082 // Update line total and total amount with tax on edit.
1083 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1084 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1085 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1088 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1089 $submittedValues['tax_amount'] = 'null';
1091 if ($lineItems[$itemId]['tax_rate']) {
1092 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1093 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1094 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1097 // CRM-10117 update the line items for participants.
1098 if (!empty($lineItems[$itemId]['price_field_id'])) {
1099 $lineItem[$this->_priceSetId
] = $lineItems;
1103 //CRM-11529 for quick config back office transactions
1104 //when financial_type_id is passed in form, update the
1105 //line items with the financial type selected in form
1106 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1108 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1109 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1113 if (!isset($submittedValues['total_amount'])) {
1114 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1116 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1118 if (!empty($submittedValues['pcp_made_through_id'])) {
1121 'pcp_made_through_id',
1122 'pcp_display_in_roll',
1123 'pcp_roll_nickname',
1124 'pcp_personal_note',
1126 foreach ($fields as $f) {
1127 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1131 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1132 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1133 //Delete existing soft credit records if soft credit list is empty on update
1134 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1137 //build soft credit params
1138 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1139 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1140 $softParams[$key]['contact_id'] = $val;
1141 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1142 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1143 if (!empty($submittedValues['soft_credit_id'][$key])) {
1144 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1150 // set the contact, when contact is selected
1151 if (!empty($submittedValues['contact_id'])) {
1152 $this->_contactID
= $submittedValues['contact_id'];
1155 // Credit Card Contribution.
1157 $this->processCreditCard($submittedValues, $lineItem);
1160 // Offline Contribution.
1161 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1163 // get the required field value only.
1164 $formValues = $submittedValues;
1165 $params = $ids = array();
1167 $params['contact_id'] = $this->_contactID
;
1169 $params['currency'] = $this->getCurrency($submittedValues);
1172 'financial_type_id',
1173 'contribution_status_id',
1174 'payment_instrument_id',
1179 foreach ($fields as $f) {
1180 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1184 $params['pcp'] = $pcp;
1186 if (!empty($softParams)) {
1187 $params['soft_credit'] = $softParams;
1188 $params['soft_credit_ids'] = $softIDs;
1191 // CRM-5740 if priceset is used, no need to cleanup money.
1193 $params['skipCleanMoney'] = 1;
1202 foreach ($dates as $d) {
1203 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1206 if (!empty($formValues['is_email_receipt'])) {
1207 $params['receipt_date'] = date("Y-m-d");
1210 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1211 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1213 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1214 $params['cancel_date'] = date('Y-m-d');
1218 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1221 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1222 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1223 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1224 $params['is_pay_later'] = 1;
1226 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1227 $params['is_pay_later'] = 0;
1230 $ids['contribution'] = $params['id'] = $this->_id
;
1232 // Add Additional common information to formatted params.
1233 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1235 $params['contribution_mode'] = 'participant';
1236 $params['participant_id'] = $pId;
1237 $params['skipLineItem'] = 1;
1239 elseif ($isRelatedId) {
1240 $params['contribution_mode'] = 'membership';
1242 $params['line_item'] = $lineItem;
1243 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1244 if (isset($submittedValues['tax_amount'])) {
1245 $params['tax_amount'] = $submittedValues['tax_amount'];
1247 //create contribution.
1248 if ($isQuickConfig) {
1249 $params['is_quick_config'] = 1;
1253 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1254 // if non_deductible_amount does NOT exist - then calculate it depending on:
1255 // $ContributionType->is_deductible and whether there is a product (premium).
1256 if (empty($params['non_deductible_amount'])) {
1257 $contributionType = new CRM_Financial_DAO_FinancialType();
1258 $contributionType->id
= $params['financial_type_id'];
1259 if (!$contributionType->find(TRUE)) {
1260 CRM_Core_Error
::fatal('Could not find a system table');
1262 if ($contributionType->is_deductible
) {
1264 if (isset($formValues['product_name'][0])) {
1265 $selectProduct = $formValues['product_name'][0];
1267 // if there is a product - compare the value to the contribution amount
1268 if (isset($selectProduct)) {
1269 $productDAO = new CRM_Contribute_DAO_Product();
1270 $productDAO->id
= $selectProduct;
1271 $productDAO->find(TRUE);
1272 // product value exceeds contribution amount
1273 if ($params['total_amount'] < $productDAO->price
) {
1274 $params['non_deductible_amount'] = $params['total_amount'];
1276 // product value does NOT exceed contribution amount
1278 $params['non_deductible_amount'] = $productDAO->price
;
1281 // contribution is deductible - but there is no product
1283 $params['non_deductible_amount'] = '0.00';
1286 // contribution is NOT deductible
1288 $params['non_deductible_amount'] = $params['total_amount'];
1292 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1294 // process associated membership / participant, CRM-4395
1295 $relatedComponentStatusMsg = NULL;
1296 if ($contribution->id
&& $this->_action
& CRM_Core_Action
::UPDATE
) {
1297 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1298 $contribution->contribution_status_id
,
1299 CRM_Utils_Array
::value('contribution_status_id',
1306 if ($contribution->id
&& isset($formValues['note'])) {
1307 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1311 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1312 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1313 $this->_premiumID
, $this->_options
1317 // assign tax calculation for contribution receipts
1319 $getTaxDetails = FALSE;
1320 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1321 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1323 if ($this->_action
& CRM_Core_Action
::ADD
) {
1326 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
1327 $line = $this->_lineItems
;
1329 foreach ($line as $key => $value) {
1330 foreach ($value as $v) {
1331 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1332 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1335 if (isset($v['tax_rate'])) {
1336 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1337 $getTaxDetails = TRUE;
1345 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1346 if (isset($submittedValues['tax_amount'])) {
1347 $totalTaxAmount = $submittedValues['tax_amount'];
1350 $totalTaxAmount = $this->_values
['tax_amount'];
1352 $this->assign('totalTaxAmount', $totalTaxAmount);
1353 $this->assign('dataArray', $taxRate);
1356 if (CRM_Utils_Array
::value('price_set_id', $submittedValues)) {
1357 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1358 $this->assign('getTaxDetails', $getTaxDetails);
1359 $this->assign('dataArray', $taxRate);
1360 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1363 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1368 //send receipt mail.
1369 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1370 $formValues['contact_id'] = $this->_contactID
;
1371 $formValues['contribution_id'] = $contribution->id
;
1373 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1375 // to get 'from email id' for send receipt
1376 $this->fromEmailId
= $formValues['from_email_address'];
1377 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues);
1380 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1386 //update pledge payment status.
1387 if ((($this->_ppID
&& $contribution->id
) && $this->_action
& CRM_Core_Action
::ADD
) ||
1388 (($pledgePaymentId) && $this->_action
& CRM_Core_Action
::UPDATE
)
1392 //store contribution id in payment record.
1393 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1396 $this->_ppID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1401 $this->_pledgeID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1408 $adjustTotalAmount = FALSE;
1409 if (CRM_Utils_Array
::value('option_type', $formValues) == 2) {
1410 $adjustTotalAmount = TRUE;
1413 $updatePledgePaymentStatus = FALSE;
1414 //do only if either the status or the amount has changed
1415 if ($this->_action
& CRM_Core_Action
::ADD
) {
1416 $updatePledgePaymentStatus = TRUE;
1418 elseif ($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $formValues['contribution_status_id']) ||
1419 ($this->_defaults
['total_amount'] != $formValues['total_amount']))
1421 $updatePledgePaymentStatus = TRUE;
1424 if ($updatePledgePaymentStatus) {
1425 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1426 array($this->_ppID
),
1427 $contribution->contribution_status_id
,
1429 $contribution->total_amount
,
1435 $statusMsg = ts('The contribution record has been saved.');
1436 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1437 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1440 if ($relatedComponentStatusMsg) {
1441 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1444 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1445 //Offline Contribution ends.
1447 $session = CRM_Core_Session
::singleton();
1448 $buttonName = $this->controller
->getButtonName();
1449 if ($this->_context
== 'standalone') {
1450 if ($buttonName == $this->getButtonName('upload', 'new')) {
1451 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1452 'reset=1&action=add&context=standalone'
1456 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1457 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1461 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1462 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1463 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1466 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1467 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1468 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1472 //store contribution ID if not yet set (on create)
1473 if (empty($this->_id
) && !empty($contribution->id
)) {
1474 $this->_id
= $contribution->id
;
1479 * Process credit card payment.
1481 * @param array $submittedValues
1482 * @param array $lineItem
1484 * @throws CRM_Core_Exception
1486 protected function processCreditCard($submittedValues, $lineItem) {
1487 $sendReceipt = $contribution = FALSE;
1489 $unsetParams = array(
1491 'payment_instrument_id',
1492 'contribution_status_id',
1496 foreach ($unsetParams as $key) {
1497 if (isset($submittedValues[$key])) {
1498 unset($submittedValues[$key]);
1501 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1502 // CRM-12680 set $_lineItem if its not set
1503 if (empty($this->_lineItem
) && !empty($lineItem)) {
1504 $this->_lineItem
= $lineItem;
1507 //Get the require fields value only.
1508 $params = $this->_params
= $submittedValues;
1510 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1514 // Get the payment processor id as per mode.
1515 $this->_params
['payment_processor'] = $params['payment_processor_id']
1516 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1518 $now = date('YmdHis');
1521 // we need to retrieve email address
1522 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1523 list($this->userDisplayName
,
1525 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1526 $this->assign('displayName', $this->userDisplayName
);
1529 // Set email for primary location.
1530 $fields['email-Primary'] = 1;
1531 $params['email-Primary'] = $this->userEmail
;
1533 // now set the values for the billing location.
1534 foreach (array_keys($this->_fields
) as $name) {
1538 // also add location name to the array
1539 $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);
1541 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1542 $fields["address_name-{$this->_bltID}"] = 1;
1543 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1548 $nameFields = array('first_name', 'middle_name', 'last_name');
1549 foreach ($nameFields as $name) {
1551 if (array_key_exists("billing_$name", $params)) {
1552 $params[$name] = $params["billing_{$name}"];
1553 $params['preserveDBName'] = TRUE;
1557 if (!empty($params['source'])) {
1558 unset($params['source']);
1560 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1566 // add all the additional payment params we need
1567 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1568 $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}"]);
1570 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1571 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1573 $legacyCreditCardExpiryCheck = FALSE;
1574 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1575 $legacyCreditCardExpiryCheck = TRUE;
1577 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1578 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1579 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1581 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1582 $this->_params
['amount'] = $this->_params
['total_amount'];
1583 $this->_params
['amount_level'] = 0;
1584 $this->_params
['description'] = ts('Office Credit Card contribution');
1585 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1587 CRM_Core_Config
::singleton()->defaultCurrency
1589 $this->_params
['payment_action'] = 'Sale';
1590 if (!empty($this->_params
['receive_date'])) {
1591 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1594 if (!empty($params['soft_credit_to'])) {
1595 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1596 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1599 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1600 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1601 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1603 //Add common data to formatted params
1604 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1606 if (empty($this->_params
['invoice_id'])) {
1607 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1610 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1613 // At this point we've created a contact and stored its address etc
1614 // all the payment processors expect the name and address to be in the
1615 // so we copy stuff over to first_name etc.
1616 $paymentParams = $this->_params
;
1617 $paymentParams['contactID'] = $this->_contactID
;
1618 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1620 $contributionType = new CRM_Financial_DAO_FinancialType();
1621 $contributionType->id
= $params['financial_type_id'];
1623 // Add some financial type details to the params list
1624 // if folks need to use it.
1625 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1626 $paymentParams['contributionPageID'] = NULL;
1628 if (!empty($this->_params
['is_email_receipt'])) {
1629 $paymentParams['email'] = $this->userEmail
;
1630 $paymentParams['is_email_receipt'] = 1;
1633 $paymentParams['is_email_receipt'] = 0;
1634 $this->_params
['is_email_receipt'] = 0;
1636 if (!empty($this->_params
['receive_date'])) {
1637 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1640 // For recurring contribution, create Contribution Record first.
1641 // Contribution ID, Recurring ID and Contact ID needed
1642 // When we get a callback from the payment processor, CRM-7115
1644 if (!empty($paymentParams['is_recur'])) {
1645 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1655 $paymentParams['contributionID'] = $contribution->id
;
1656 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1657 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1658 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1661 if ($paymentParams['amount'] > 0.0) {
1662 // force a re-get of the payment processor in case the form changed it, CRM-7179
1663 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1665 $result = $payment->doPayment($paymentParams, 'contribute');
1667 catch (CRM_Core_Exception
$e) {
1668 $message = ts("Payment Processor Error message") . $e->getMessage();
1669 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1670 // Set the contribution mode.
1671 $urlParams = "action=add&cid={$this->_contactID}";
1673 $urlParams .= "&mode={$this->_mode}";
1675 if (!empty($this->_ppID
)) {
1676 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1678 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1682 $this->_params
= array_merge($this->_params
, $result);
1684 $this->_params
['receive_date'] = $now;
1686 if (!empty($this->_params
['is_email_receipt'])) {
1687 $this->_params
['receipt_date'] = $now;
1690 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1691 $params['receipt_date_time'], TRUE
1695 $this->set('params', $this->_params
);
1696 $this->assign('trxn_id', $result['trxn_id']);
1697 $this->assign('receive_date', $this->_params
['receive_date']);
1699 // Result has all the stuff we need
1700 // lets archive it to a financial transaction
1701 if ($contributionType->is_deductible
) {
1702 $this->assign('is_deductible', TRUE);
1703 $this->set('is_deductible', TRUE);
1706 // Set source if not set
1707 if (empty($this->_params
['source'])) {
1708 $userID = CRM_Core_Session
::singleton()->get('userID');
1709 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1712 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1715 // Build custom data getFields array
1716 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1717 CRM_Utils_Array
::value('financial_type_id', $params)
1719 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1720 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1722 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1727 if (empty($paymentParams['is_recur'])) {
1728 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1739 // Send receipt mail.
1740 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1741 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1742 $this->_params
['contact_id'] = $this->_contactID
;
1743 $this->_params
['contribution_id'] = $contribution->id
;
1744 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1748 if ($contribution->id
&& isset($params['note'])) {
1749 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1752 if ($contribution->id
&& isset($params['product_name'][0])) {
1753 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1756 //update pledge payment status.
1757 if ($this->_ppID
&& $contribution->id
) {
1758 // Store contribution id in payment record.
1759 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1761 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1762 array($this->_ppID
),
1763 $contribution->contribution_status_id
,
1765 $contribution->total_amount
1769 if ($contribution->id
) {
1770 $statusMsg = ts('The contribution record has been processed.');
1771 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1772 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1774 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1779 * Clean up DB after payment fails.
1781 * This function removes related DB entries. Note that it has been agreed in principle,
1782 * but not implemented, that contributions should be retained as 'Failed' rather than
1785 * @todo it doesn't clean up line items.
1787 * @param array $paymentParams
1788 * @param string $message
1790 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1791 // Make sure to cleanup db for recurring case.
1792 if (!empty($paymentParams['contributionID'])) {
1793 CRM_Core_Error
::debug_log_message($message .
1794 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1795 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1797 if (!empty($paymentParams['contributionRecurID'])) {
1798 CRM_Core_Error
::debug_log_message($message .
1799 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1800 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1805 * Generate the data to construct a snippet based pane.
1807 * This form also assigns the showAdditionalInfo var based on historical code.
1808 * This appears to mean 'there is a pane to show'.
1810 * @param string $type
1811 * Type of Pane - this is generally used to determine the function name used to build it
1812 * - e.g CreditCard, AdditionalDetail
1813 * @param array $defaults
1816 * We aim to further refactor & simplify this but currently
1818 * - should additional info be shown?
1820 protected function generatePane($type, $defaults) {
1821 $urlParams = "snippet=4&formType={$type}";
1823 $urlParams .= "&mode={$this->_mode}";
1827 if ($type == 'CreditCard' ||
1828 $type == 'DirectDebit'
1834 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1839 // See if we need to include this paneName in the current form.
1840 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1841 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1843 $this->assign('showAdditionalInfo', TRUE);
1844 $pane['open'] = 'true';
1847 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1848 // @todo would be good to align tpl name with form name...
1849 // @todo document why this hidden variable is required.
1850 $this->add('hidden', 'hidden_' . $type, 1);
1854 $additionalInfoFormFunction = 'build' . $type;
1855 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);