3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 usefusul, 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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class generates form components for processing a contribution
40 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
42 * the id of the contribution that we are processing
50 * the id of the premium that we are processing
55 public $_premiumID = NULL;
58 * @var CRM_Contribute_DAO_ContributionProduct
60 public $_productDAO = NULL;
71 * the id of the contact associated with this contribution
79 * the id of the pledge payment that we are processing
87 * the id of the pledge that we are processing
95 * is this contribution associated with an online
96 * financial transaction
101 public $_online = FALSE;
104 * Stores all product option
112 * Storage of parameters from form
120 * Store the contribution Type ID
124 public $_contributionType;
127 * The contribution values if an existing contribution
132 * The pledge values if this contribution is associated with pledge
134 public $_pledgeValues;
136 public $_contributeMode = 'direct';
141 * Parameter with confusing name
145 public $_compContext;
150 * Possible From email addresses
161 * Store the line items if price set used.
167 * @todo explain why we use lineItem & lineItems
173 * @var array soft credit info
175 public $_softCreditInfo;
177 protected $_formType;
180 * @todo what on earth does cdType stand for????
184 public $_honoreeProfileType;
187 * array of billing panes to be displayed by billingBlock.tpl - currently this is likely to look like
188 * array('Credit Card' => ts('Credit Card') or array('Direct Debit => ts('Direct Debit')
189 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
193 public $billingPane = array();
196 * array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
197 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
201 public $_paymentFields = array();
203 * logged in user's email
216 * Price set as an array
223 * @todo can we define this a as protected? can we define higher up the chain
233 public $userDisplayName;
235 * Function to set variables up before form is built
240 public function preProcess() {
242 //check permission for action.
243 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
244 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
247 //@todo - if anyone ever figures out what this cdtype subroutine is about (or even if it still applies) please add comments
248 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
249 $this->assign('cdType', FALSE);
250 if ($this->_cdType
) {
251 $this->assign('cdType', TRUE);
252 CRM_Custom_Form_CustomData
::preProcess($this);
256 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
259 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
260 $this->set('priceSetId', $this->_priceSetId
);
261 $this->assign('priceSetId', $this->_priceSetId
);
263 //get the pledge payment id
264 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
267 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
270 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
271 $this->assign('action', $this->_action
);
273 //get the contribution id if update
274 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
275 if (!empty($this->_id
)) {
276 $this->assign('contribID', $this->_id
);
279 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
280 $this->assign('context', $this->_context
);
282 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
284 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
286 //set the contribution mode.
287 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
289 $this->assign('contributionMode', $this->_mode
);
290 if ($this->_action
& CRM_Core_Action
::DELETE
) {
294 $this->assign('showCheckNumber', TRUE);
296 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
297 $this->assignPaymentRelatedVariables();
299 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
300 $this->preProcessPledge();
304 $this->showRecordLinkMesssage($this->_id
);
306 $this->_values
= array();
308 // current contribution id
310 $this->assignPremiumProduct($this->_id
);
311 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
314 // when custom data is included in this page
315 if (!empty($_POST['hidden_custom'])) {
316 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
319 $this->_lineItems
= array();
321 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
322 $this->assign('compId', $this->_compId
);
323 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
326 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
328 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
331 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
335 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
338 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
342 CRM_Contribute_Form_SoftCredit
::preprocess($this);
346 function setDefaultValues() {
347 if ($this->_cdType
) {
348 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
351 $defaults = $this->_values
;
353 //set defaults for pledge payment.
355 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
356 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
357 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
358 $defaults['option_type'] = 1;
361 if ($this->_action
& CRM_Core_Action
::DELETE
) {
365 // set soft credit defaults
366 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
369 $config = CRM_Core_Config
::singleton();
370 // set default country from config if no country set
371 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
372 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
375 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
376 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
379 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
380 $defaults = array_merge($defaults, $billingDefaults);
384 $this->_contactID
= $defaults['contact_id'];
387 // Set $newCredit variable in template to control whether link to credit card mode is included
388 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
390 // fix the display of the monetary value, CRM-4038
391 if (isset($defaults['total_amount'])) {
392 if (!empty($defaults['tax_amount'])) {
393 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
394 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
395 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
399 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
403 if (isset($defaults['non_deductible_amount'])) {
404 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
407 if (isset($defaults['fee_amount'])) {
408 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
411 if (isset($defaults['net_amount'])) {
412 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
415 if ($this->_contributionType
) {
416 $defaults['financial_type_id'] = $this->_contributionType
;
419 if (empty($defaults['payment_instrument_id'])) {
420 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
423 if (!empty($defaults['is_test'])) {
424 $this->assign('is_test', TRUE);
427 $this->assign('showOption', TRUE);
428 // for Premium section
429 if ($this->_premiumID
) {
430 $this->assign('showOption', FALSE);
431 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
433 $this->assign('showOption', TRUE);
435 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
437 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
440 $defaults['product_name'] = array($this->_productDAO
->product_id
);
442 if ($this->_productDAO
->fulfilled_date
) {
443 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
447 if (isset($this->userEmail
)) {
448 $this->assign('email', $this->userEmail
);
451 if (!empty($defaults['is_pay_later'])) {
452 $this->assign('is_pay_later', TRUE);
454 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
456 $dates = array('receive_date', 'receipt_date', 'cancel_date', 'thankyou_date');
457 foreach ($dates as $key) {
458 if (!empty($defaults[$key])) {
459 list($defaults[$key],
460 $defaults[$key . '_time']
461 ) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults),
467 if (!$this->_id
&& empty($defaults['receive_date'])) {
468 list($defaults['receive_date'],
469 $defaults['receive_date_time']
470 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
473 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
474 CRM_Utils_Array
::value('receive_date_time', $defaults)
476 $currency = CRM_Utils_Array
::value('currency', $defaults);
477 $this->assign('currency', $currency);
478 // Hack to get currency info to the js layer. CRM-11440
479 CRM_Utils_Money
::format(1);
480 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
481 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
483 //inherit campaign from pledge.
484 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
485 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
488 $this->_defaults
= $defaults;
493 * Function to build the form
498 public function buildQuickForm() {
499 //@todo document the purpose of cdType (if still in use)
500 if ($this->_cdType
) {
501 CRM_Custom_Form_CustomData
::buildQuickForm($this);
505 //tax rate from financialType
506 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
507 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
509 // build price set form.
510 $buildPriceSet = FALSE;
511 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
512 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
513 $this->assign('invoicing', $invoicing);
515 // display tax amount on edit contribution page
516 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
517 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
520 if (empty($this->_lineItems
) &&
521 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
523 $buildPriceSet = TRUE;
524 $getOnlyPriceSetElements = TRUE;
525 if (!$this->_priceSetId
) {
526 $this->_priceSetId
= $_POST['price_set_id'];
527 $getOnlyPriceSetElements = FALSE;
530 $this->set('priceSetId', $this->_priceSetId
);
531 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
533 // get only price set form elements.
534 if ($getOnlyPriceSetElements) {
538 // use to build form during form rule.
539 $this->assign('buildPriceSet', $buildPriceSet);
541 $showAdditionalInfo = FALSE;
543 $defaults = $this->_values
;
544 $additionalDetailFields = array(
548 'non_deductible_amount',
552 foreach ($additionalDetailFields as $key) {
553 if (!empty($defaults[$key])) {
554 $defaults['hidden_AdditionalDetail'] = 1;
559 if ($this->_productDAO
) {
560 if ($this->_productDAO
->product_id
) {
561 $defaults['hidden_Premium'] = 1;
565 if ($this->_noteID
&&
566 isset($this->_values
['note'])
568 $defaults['hidden_AdditionalDetail'] = 1;
572 ts('Additional Details') => 'AdditionalDetail',
575 //Add Premium pane only if Premium is exists.
576 $dao = new CRM_Contribute_DAO_Product();
579 if ($dao->find(TRUE)) {
580 $paneNames[ts('Premium Information')] = 'Premium';
584 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
585 $buildRecurBlock = TRUE;
586 foreach ($this->billingPane
as $name => $label) {
587 if (!empty($this->billingFieldSets
[$name]['fields'])) {
588 //@todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
589 $paneNames[$label] = CRM_Utils_String
::convertStringToCamel($name);
595 foreach ($paneNames as $name => $type) {
596 $urlParams = "snippet=4&formType={$type}";
598 $urlParams .= "&mode={$this->_mode}";
602 if ($type == 'CreditCard' ||
603 $type == 'DirectDebit'
608 $allPanes[$name] = array(
609 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
614 // see if we need to include this paneName in the current form
615 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
616 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
618 $showAdditionalInfo = TRUE;
619 $allPanes[$name]['open'] = 'true';
622 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
623 //@todo would be good to align tpl name with form name...
624 $this->add('hidden', 'hidden_' . $type, 1);
627 $additionalInfoFormFunction = 'build' . $type;
628 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
631 if (empty($this->_recurPaymentProcessors
)) {
632 $buildRecurBlock = FALSE;
634 if ($buildRecurBlock) {
635 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
636 $this->setDefaults(array('is_recur' => 0));
638 $this->assign('buildRecurBlock', $buildRecurBlock);
639 $qfKey = $this->controller
->_key
;
640 $this->assign('qfKey', $qfKey);
641 $this->assign('allPanes', $allPanes);
642 $this->assign('showAdditionalInfo', $showAdditionalInfo);
644 if ($this->_formType
) {
645 $this->assign('formType', $this->_formType
);
649 $this->applyFilter('__ALL__', 'trim');
651 if ($this->_action
& CRM_Core_Action
::DELETE
) {
652 $this->addButtons(array(
655 'name' => ts('Delete'),
656 'spacing' => ' ',
661 'name' => ts('Cancel')
668 //need to assign custom data type and subtype to the template
669 $this->assign('customDataType', 'Contribution');
670 $this->assign('customDataSubType', $this->_contributionType
);
671 $this->assign('entityID', $this->_id
);
673 if ($this->_context
== 'standalone') {
674 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
677 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
679 $financialType = $this->add('select', 'financial_type_id',
680 ts('Financial Type'),
681 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
683 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
685 $paymentInstrument = FALSE;
687 $paymentInstrument = $this->add('select', 'payment_instrument_id',
689 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
690 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
694 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
696 //add receipt for offline contribution
697 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
699 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
701 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
703 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
704 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
711 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
714 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
715 $suppressFlag = FALSE;
717 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
718 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
719 $suppressFlag = TRUE;
722 if (!$suppressFlag) {
727 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
731 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
736 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
737 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
742 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
743 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
744 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
748 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
758 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
764 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
767 $this->add('select', 'contribution_status_id',
768 ts('Contribution Status'),
774 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
776 if ($this->_online
) {
777 $this->assign('hideCalender', TRUE);
779 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
781 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
782 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
784 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
787 if ($buildRecurBlock) {
788 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
790 $element = $this->add('select',
791 'payment_processor_id',
792 ts('Payment Processor'),
798 if ($this->_online
) {
802 if (empty($this->_lineItems
)) {
803 $buildPriceSet = FALSE;
804 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
805 if (!empty($priceSets) && !$this->_ppID
) {
806 $buildPriceSet = TRUE;
809 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
810 // and if we already have line items for that participant. CRM-5095
811 if ($buildPriceSet && $this->_id
) {
812 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
813 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
818 if ($pledgePaymentId) {
819 $buildPriceSet = FALSE;
821 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
822 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
823 if (!CRM_Utils_System
::isNull($participantLI)) {
824 $buildPriceSet = FALSE;
829 $hasPriceSets = FALSE;
830 if ($buildPriceSet) {
831 $hasPriceSets = TRUE;
832 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
834 '' => ts('Choose price set')
836 NULL, array('onchange' => "buildAmount( this.value );")
838 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
842 $this->assign('hasPriceSets', $hasPriceSets);
843 $currencyFreeze = FALSE;
844 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
845 if ($this->_online ||
$this->_ppID
) {
846 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
848 'style' => "background-color:#EBECE4"
850 $optionTypes = array(
851 '1' => ts('Adjust Pledge Payment Schedule?'),
852 '2' => ts('Adjust Total Pledge Amount?'),
854 $this->addRadio('option_type',
860 $currencyFreeze = TRUE;
864 $totalAmount = $this->addMoney('total_amount',
866 ($hasPriceSets) ?
FALSE : TRUE,
867 $attributes['total_amount'],
868 TRUE, 'currency', NULL, $currencyFreeze
872 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
874 //CRM-7362 --add campaigns.
875 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
877 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
881 $js = array('onclick' => "return verify( );");
884 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
887 $this->assign('outBound_option', $mailingInfo['outBound_option']);
889 $this->addButtons(array(
892 'name' => ts('Save'),
898 'name' => ts('Save and New'),
904 'name' => ts('Cancel')
909 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
910 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
911 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
913 $totalAmount->freeze();
915 $checkNumber->freeze();
916 $paymentInstrument->freeze();
918 $financialType->freeze();
921 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
923 // if contribution is related to membership or participant freeze Financial Type, Amount
924 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
925 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
926 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
927 $financialType->freeze();
928 $totalAmount->freeze();
929 $this->assign('freezeFinancialType', TRUE);
933 if ($this->_action
& CRM_Core_Action
::VIEW
) {
941 * @param array $fields the input form values
942 * @param array $files the uploaded files if any
945 * @internal param array $options additional user data
947 * @return true if no errors, else array of errors
951 static function formRule($fields, $files, $self) {
954 //check for Credit Card Contribution.
956 if (empty($fields['payment_processor_id'])) {
957 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
961 // do the amount validations.
962 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
963 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
964 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
968 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
970 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
971 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
972 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
973 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
976 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
977 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
978 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
981 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
982 if (!empty($fields['fee_amount']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
983 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
986 // $trxn_id must be unique CRM-13919
987 if (!empty($fields['trxn_id'])) {
988 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
989 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
991 $queryParams[2] = array((int)$self->_id
, 'Integer');
992 $query .= ' and id !=%2';
994 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
996 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
1000 $errors = array_merge($errors, $softErrors);
1005 * Function to process the form
1011 public function postProcess() {
1012 $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
1013 $softParams = $softIDs =array();
1015 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1016 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1017 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1018 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1023 // get the submitted form values.
1024 $submittedValues = $this->controller
->exportValues($this->_name
);
1025 if (!empty($submittedValues['price_set_id']) && $this->_action
& CRM_Core_Action
::UPDATE
) {
1026 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1027 $lineID = key($line);
1028 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1029 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1031 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1035 // process price set and get total amount and line items.
1036 $lineItem = array();
1037 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1038 if (empty($priceSetId) && !$this->_id
) {
1039 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1040 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1041 $fieldID = key($this->_priceSet
['fields']);
1042 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1043 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1044 $submittedValues['price_' . $fieldID] = 1;
1048 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1049 $submittedValues, $lineItem[$priceSetId]);
1051 // unset tax amount for offline 'is_quick_config' contribution
1052 if ($this->_priceSet
['is_quick_config'] &&
1053 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1055 unset($submittedValues['tax_amount']);
1057 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1060 if ($this->_compId
) {
1061 if ($this->_context
== 'participant') {
1062 $pId = $this->_compId
;
1064 elseif ($this->_context
== 'membership') {
1065 $isRelatedId = TRUE;
1068 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1072 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1073 if (array_key_exists('membership', $contributionDetails)) {
1074 $isRelatedId = TRUE;
1076 elseif (array_key_exists('participant', $contributionDetails)) {
1077 $pId = current($contributionDetails['participant']);
1083 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1087 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1088 // 10117 update th line items for participants
1090 $entityTable = 'participant';
1092 $isRelatedId = FALSE;
1093 $participantParams = array(
1094 'fee_amount' => $submittedValues['total_amount'],
1097 CRM_Event_BAO_Participant
::add($participantParams);
1098 if (empty($this->_lineItems
)) {
1099 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1103 $entityTable = 'contribution';
1104 $entityID = $this->_id
;
1107 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, $isQuickConfig, $isRelatedId);
1108 foreach (array_keys($lineItems) as $id) {
1109 $lineItems[$id]['id'] = $id;
1111 $itemId = key($lineItems);
1112 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1113 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1116 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1117 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1119 // Update line total and total amount with tax on edit
1120 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1121 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1122 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1125 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "" ;
1126 $submittedValues['tax_amount'] = 'null';
1128 if ($lineItems[$itemId]['tax_rate']) {
1129 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate']/100) * $lineItems[$itemId]['line_total'];
1130 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1131 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1134 // 10117 update th line items for participants
1135 if (!empty($lineItems[$itemId]['price_field_id'])) {
1136 $lineItem[$this->_priceSetId
] = $lineItems;
1140 //CRM-11529 for quick config back office transactions
1141 //when financial_type_id is passed in form, update the
1142 //line items with the financial type selected in form
1143 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1145 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1146 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1150 if (!isset($submittedValues['total_amount'])) {
1151 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1153 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1155 if (!empty($submittedValues['pcp_made_through_id'])) {
1158 'pcp_made_through_id',
1159 'pcp_display_in_roll',
1160 'pcp_roll_nickname',
1161 'pcp_personal_note',
1163 foreach ($fields as $f) {
1164 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1168 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1169 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1170 //Delete existing soft credit records if soft credit list is empty on update
1171 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1174 //build soft credit params
1175 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1176 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1177 $softParams[$key]['contact_id'] = $val;
1178 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1179 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1180 if (!empty($submittedValues['soft_credit_id'][$key])) {
1181 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1187 // set the contact, when contact is selected
1188 if (!empty($submittedValues['contact_id'])) {
1189 $this->_contactID
= $submittedValues['contact_id'];
1192 $config = CRM_Core_Config
::singleton();
1194 //Credit Card Contribution.
1196 $session = CRM_Core_Session
::singleton();
1197 $this->processCreditCard($submittedValues, $config, $session, $lineItem);
1200 //Offline Contribution.
1201 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1203 // get the required field value only.
1204 $formValues = $submittedValues;
1205 $params = $ids = array();
1207 $params['contact_id'] = $this->_contactID
;
1209 $params['currency'] = $this->getCurrency($submittedValues);
1212 'financial_type_id',
1213 'contribution_status_id',
1214 'payment_instrument_id',
1219 foreach ($fields as $f) {
1220 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1224 $params['pcp'] = $pcp;
1226 if (!empty($softParams)) {
1227 $params['soft_credit'] = $softParams;
1228 $params['soft_credit_ids'] = $softIDs;
1231 //if priceset is used, no need to cleanup money
1234 $params['skipCleanMoney'] = 1;
1243 foreach ($dates as $d) {
1244 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1247 if (!empty($formValues['is_email_receipt'])) {
1248 $params['receipt_date'] = date("Y-m-d");
1251 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1252 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1254 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1255 $params['cancel_date'] = date('Y-m-d');
1259 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1262 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1263 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1264 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1265 $params['is_pay_later'] = 1;
1267 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1268 $params['is_pay_later'] = 0;
1271 $ids['contribution'] = $params['id'] = $this->_id
;
1273 //Add Additional common information to formatted params
1274 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1276 $params['contribution_mode'] = 'participant';
1277 $params['participant_id'] = $pId;
1278 $params['skipLineItem'] = 1;
1280 elseif ($isRelatedId) {
1281 $params['contribution_mode'] = 'membership';
1283 $params['line_item'] = $lineItem;
1284 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1285 if (isset($submittedValues['tax_amount'])) {
1286 $params['tax_amount'] = $submittedValues['tax_amount'];
1288 //create contribution.
1289 if ($isQuickConfig) {
1290 $params['is_quick_config'] = 1;
1294 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1295 // if non_deductible_amount does NOT exist - then calculate it depending on:
1296 // $ContributionType->is_deductible and whether there is a product (premium).
1297 if (empty($params['non_deductible_amount'])) {
1298 $contributionType = new CRM_Financial_DAO_FinancialType();
1299 $contributionType->id
= $params['financial_type_id'];
1300 if (!$contributionType->find(TRUE)) {
1301 CRM_Core_Error
::fatal('Could not find a system table');
1303 if ($contributionType->is_deductible
) {
1305 if (isset($formValues['product_name'][0])) {
1306 $selectProduct = $formValues['product_name'][0];
1308 // if there is a product - compare the value to the contribution amount
1309 if (isset($selectProduct)) {
1310 $productDAO = new CRM_Contribute_DAO_Product();
1311 $productDAO->id
= $selectProduct;
1312 $productDAO->find(TRUE);
1313 // product value exceeds contribution amount
1314 if ($params['total_amount'] < $productDAO->price
) {
1315 $params['non_deductible_amount'] = $params['total_amount'];
1317 // product value does NOT exceed contribution amount
1319 $params['non_deductible_amount'] = $productDAO->price
;
1322 // contribution is deductible - but there is no product
1324 $params['non_deductible_amount'] = '0.00';
1327 // contribution is NOT deductible
1329 $params['non_deductible_amount'] = $params['total_amount'];
1333 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1335 // process associated membership / participant, CRM-4395
1336 $relatedComponentStatusMsg = NULL;
1337 if ($contribution->id
&& $this->_action
& CRM_Core_Action
::UPDATE
) {
1338 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1339 $contribution->contribution_status_id
,
1340 CRM_Utils_Array
::value('contribution_status_id',
1347 if ($contribution->id
&& isset($formValues['note'])) {
1348 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1352 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1353 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1354 $this->_premiumID
, $this->_options
1358 // assign tax calculation for contribution receipts
1360 $getTaxDetails = FALSE;
1361 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
1362 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1364 if ($this->_action
& CRM_Core_Action
::ADD
) {
1367 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
1368 $line = $this->_lineItems
;
1370 foreach ($line as $key => $value) {
1371 foreach ($value as $v) {
1372 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1373 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1376 if (isset($v['tax_rate'])) {
1377 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1378 $getTaxDetails = TRUE;
1386 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1387 if (isset($submittedValues['tax_amount'])) {
1388 $totalTaxAmount = $submittedValues['tax_amount'];
1391 $totalTaxAmount = $this->_values
['tax_amount'];
1393 $this->assign('totalTaxAmount', $totalTaxAmount);
1394 $this->assign('dataArray', $taxRate);
1397 if (CRM_Utils_Array
::value('price_set_id', $submittedValues)) {
1398 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1399 $this->assign('getTaxDetails', $getTaxDetails);
1400 $this->assign('dataArray', $taxRate);
1401 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1404 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1409 //send receipt mail.
1410 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1411 $formValues['contact_id'] = $this->_contactID
;
1412 $formValues['contribution_id'] = $contribution->id
;
1414 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1416 // to get 'from email id' for send receipt
1417 $this->fromEmailId
= $formValues['from_email_address'];
1418 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues);
1421 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1427 //update pledge payment status.
1428 if ((($this->_ppID
&& $contribution->id
) && $this->_action
& CRM_Core_Action
::ADD
) ||
1429 (($pledgePaymentId) && $this->_action
& CRM_Core_Action
::UPDATE
)
1433 //store contribution id in payment record.
1434 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1437 $this->_ppID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1442 $this->_pledgeID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1449 $adjustTotalAmount = FALSE;
1450 if (CRM_Utils_Array
::value('option_type', $formValues) == 2) {
1451 $adjustTotalAmount = TRUE;
1454 $updatePledgePaymentStatus = FALSE;
1455 //do only if either the status or the amount has changed
1456 if ($this->_action
& CRM_Core_Action
::ADD
) {
1457 $updatePledgePaymentStatus = TRUE;
1459 elseif ($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $formValues['contribution_status_id']) ||
1460 ($this->_defaults
['total_amount'] != $formValues['total_amount']))
1462 $updatePledgePaymentStatus = TRUE;
1465 if ($updatePledgePaymentStatus) {
1466 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1467 array($this->_ppID
),
1468 $contribution->contribution_status_id
,
1470 $contribution->total_amount
,
1476 $statusMsg = ts('The contribution record has been saved.');
1477 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1478 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1481 if ($relatedComponentStatusMsg) {
1482 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1485 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1486 //Offline Contribution ends.
1488 $session = CRM_Core_Session
::singleton();
1489 $buttonName = $this->controller
->getButtonName();
1490 if ($this->_context
== 'standalone') {
1491 if ($buttonName == $this->getButtonName('upload', 'new')) {
1492 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1493 'reset=1&action=add&context=standalone'
1497 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1498 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1502 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1503 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1504 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1507 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1508 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1509 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1513 //store contribution ID if not yet set (on create)
1514 if ( empty($this->_id
) && !empty($contribution->id
) ) {
1515 $this->_id
= $contribution->id
;
1520 * @param $submittedValues
1522 * @param $session CRM_Core_Session
1525 * @throws CRM_Core_Exception
1527 public function processCreditCard($submittedValues, $config, $session, $lineItem) {
1528 $sendReceipt = $contribution = FALSE;
1530 $unsetParams = array(
1532 'payment_instrument_id',
1533 'contribution_status_id',
1537 foreach ($unsetParams as $key) {
1538 if (isset($submittedValues[$key])) {
1539 unset($submittedValues[$key]);
1542 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1543 // CRM-12680 set $_lineItem if its not set
1544 if (empty($this->_lineItem
) && !empty($lineItem)) {
1545 $this->_lineItem
= $lineItem;
1548 //Get the require fields value only.
1549 $params = $this->_params
= $submittedValues;
1551 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1555 //get the payment processor id as per mode.
1556 $this->_params
['payment_processor'] = $params['payment_processor_id'] =
1557 $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1559 $now = date('YmdHis');
1562 // we need to retrieve email address
1563 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1564 list($this->userDisplayName
,
1566 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1567 $this->assign('displayName', $this->userDisplayName
);
1570 //set email for primary location.
1571 $fields['email-Primary'] = 1;
1572 $params['email-Primary'] = $this->userEmail
;
1574 // now set the values for the billing location.
1575 foreach (array_keys($this->_fields
) as $name) {
1579 // also add location name to the array
1580 $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);
1582 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1583 $fields["address_name-{$this->_bltID}"] = 1;
1584 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1589 $nameFields = array('first_name', 'middle_name', 'last_name');
1590 foreach ($nameFields as $name) {
1592 if (array_key_exists("billing_$name", $params)) {
1593 $params[$name] = $params["billing_{$name}"];
1594 $params['preserveDBName'] = TRUE;
1598 if (!empty($params['source'])) {
1599 unset($params['source']);
1601 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1607 // add all the additional payment params we need
1608 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1609 $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}"]);
1611 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1612 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1614 $legacyCreditCardExpiryCheck = FALSE;
1615 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1616 $legacyCreditCardExpiryCheck = TRUE;
1618 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1619 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1620 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1622 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1623 $this->_params
['amount'] = $this->_params
['total_amount'];
1624 $this->_params
['amount_level'] = 0;
1625 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1627 $config->defaultCurrency
1629 $this->_params
['payment_action'] = 'Sale';
1630 if (!empty($this->_params
['receive_date'])) {
1631 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1634 if (!empty($params['soft_credit_to'])) {
1635 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1636 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1639 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1640 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1641 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1643 //Add common data to formatted params
1644 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1646 if (empty($this->_params
['invoice_id'])) {
1647 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1650 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1653 // at this point we've created a contact and stored its address etc
1654 // all the payment processors expect the name and address to be in the
1655 // so we copy stuff over to first_name etc.
1656 $paymentParams = $this->_params
;
1657 $paymentParams['contactID'] = $this->_contactID
;
1658 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1660 $contributionType = new CRM_Financial_DAO_FinancialType();
1661 $contributionType->id
= $params['financial_type_id'];
1663 // add some financial type details to the params list
1664 // if folks need to use it
1665 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1666 $paymentParams['contributionPageID'] = NULL;
1668 if (!empty($this->_params
['is_email_receipt'])) {
1669 $paymentParams['email'] = $this->userEmail
;
1670 $paymentParams['is_email_receipt'] = 1;
1673 $paymentParams['is_email_receipt'] = 0;
1674 $this->_params
['is_email_receipt'] = 0;
1676 if (!empty($this->_params
['receive_date'])) {
1677 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1680 // For recurring contribution, create Contribution Record first.
1681 // Contribution ID, Recurring ID and Contact ID needed
1682 // When we get a callback from the payment processor, CRM-7115
1684 if (!empty($paymentParams['is_recur'])) {
1685 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1695 $paymentParams['contributionID'] = $contribution->id
;
1696 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1697 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1698 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1701 if ($paymentParams['amount'] > 0.0) {
1702 // force a re-get of the payment processor in case the form changed it, CRM-7179
1703 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1705 $result = $payment->doPayment($paymentParams, 'contribute');
1707 catch (CRM_Core_Exception
$e) {
1708 $message = ts("Payment Processor Error message") . $e->getMessage();
1709 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1710 //set the contribution mode.
1711 $urlParams = "action=add&cid={$this->_contactID}";
1713 $urlParams .= "&mode={$this->_mode}";
1715 if (!empty($this->_ppID
)) {
1716 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1718 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1722 $this->_params
= array_merge($this->_params
, $result);
1724 $this->_params
['receive_date'] = $now;
1726 if (!empty($this->_params
['is_email_receipt'])) {
1727 $this->_params
['receipt_date'] = $now;
1730 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1731 $params['receipt_date_time'], TRUE
1735 $this->set('params', $this->_params
);
1736 $this->assign('trxn_id', $result['trxn_id']);
1737 $this->assign('receive_date', $this->_params
['receive_date']);
1739 // result has all the stuff we need
1740 // lets archive it to a financial transaction
1741 if ($contributionType->is_deductible
) {
1742 $this->assign('is_deductible', TRUE);
1743 $this->set('is_deductible', TRUE);
1746 // set source if not set
1747 if (empty($this->_params
['source'])) {
1748 $userID = $session->get('userID');
1749 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1752 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1755 // build custom data getFields array
1756 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1757 CRM_Utils_Array
::value('financial_type_id', $params)
1759 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1760 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1762 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1769 if (empty($paymentParams['is_recur'])) {
1770 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1781 //send receipt mail.
1782 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1783 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1784 $this->_params
['contact_id'] = $this->_contactID
;
1785 $this->_params
['contribution_id'] = $contribution->id
;
1786 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1790 if ($contribution->id
&& isset($params['note'])) {
1791 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1794 if ($contribution->id
&& isset($params['product_name'][0])) {
1795 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1798 //update pledge payment status.
1799 if ($this->_ppID
&& $contribution->id
) {
1800 //store contribution id in payment record.
1801 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1803 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1804 array($this->_ppID
),
1805 $contribution->contribution_status_id
,
1807 $contribution->total_amount
1811 if ($contribution->id
) {
1812 $statusMsg = ts('The contribution record has been processed.');
1813 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1814 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1816 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1821 * @param $paymentParams
1825 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1826 //make sure to cleanup db for recurring case.
1827 if (!empty($paymentParams['contributionID'])) {
1828 CRM_Core_Error
::debug_log_message($message .
1829 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1830 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1832 if (!empty($paymentParams['contributionRecurID'])) {
1833 CRM_Core_Error
::debug_log_message($message .
1834 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1835 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);