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 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
49 * The id of the premium that we are processing
53 public $_premiumID = NULL;
56 * @var CRM_Contribute_DAO_ContributionProduct
58 public $_productDAO = NULL;
68 * The id of the contact associated with this contribution
75 * The id of the pledge payment that we are processing
82 * The id of the pledge that we are processing
89 * Is this contribution associated with an online
90 * financial transaction
94 public $_online = FALSE;
97 * Stores all product option
104 * Storage of parameters from form
111 * Store the contribution Type ID
115 public $_contributionType;
118 * The contribution values if an existing contribution
123 * The pledge values if this contribution is associated with pledge
125 public $_pledgeValues;
127 public $_contributeMode = 'direct';
132 * Parameter with confusing name
136 public $_compContext;
141 * Possible From email addresses
153 * Store the line items if price set used.
159 * @todo explain why we use lineItem & lineItems
165 * @var array soft credit info
167 public $_softCreditInfo;
169 protected $_formType;
172 * @todo what on earth does cdType stand for????
176 public $_honoreeProfileType;
179 * Array of billing panes to be displayed by billingBlock.tpl - currently this is likely to look like
180 * array('Credit Card' => ts('Credit Card') or array('Direct Debit => ts('Direct Debit')
181 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
185 public $billingPane = array();
188 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
189 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
193 public $_paymentFields = array();
195 * Logged in user's email
208 * Price set as an array
215 * @todo can we define this a as protected? can we define higher up the chain
225 public $userDisplayName;
228 * Set variables up before form is built
232 public function preProcess() {
234 //check permission for action.
235 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
236 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
239 //@todo - if anyone ever figures out what this cdtype subroutine is about (or even if it still applies) please add comments
240 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
241 $this->assign('cdType', FALSE);
242 if ($this->_cdType
) {
243 $this->assign('cdType', TRUE);
244 CRM_Custom_Form_CustomData
::preProcess($this);
248 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
251 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
252 $this->set('priceSetId', $this->_priceSetId
);
253 $this->assign('priceSetId', $this->_priceSetId
);
255 //get the pledge payment id
256 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
259 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
262 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
263 $this->assign('action', $this->_action
);
265 //get the contribution id if update
266 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
267 if (!empty($this->_id
)) {
268 $this->assign('contribID', $this->_id
);
271 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
272 $this->assign('context', $this->_context
);
274 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
276 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
278 //set the contribution mode.
279 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
281 $this->assign('contributionMode', $this->_mode
);
282 if ($this->_action
& CRM_Core_Action
::DELETE
) {
286 $this->assign('showCheckNumber', TRUE);
288 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
289 $this->assignPaymentRelatedVariables();
291 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
292 $this->preProcessPledge();
296 $this->showRecordLinkMesssage($this->_id
);
298 $this->_values
= array();
300 // current contribution id
302 $this->assignPremiumProduct($this->_id
);
303 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
306 // when custom data is included in this page
307 if (!empty($_POST['hidden_custom'])) {
308 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
311 $this->_lineItems
= array();
313 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
314 $this->assign('compId', $this->_compId
);
315 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
318 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
320 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
323 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
327 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
330 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
334 CRM_Contribute_Form_SoftCredit
::preprocess($this);
338 public function setDefaultValues() {
339 if ($this->_cdType
) {
340 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
343 $defaults = $this->_values
;
345 //set defaults for pledge payment.
347 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
348 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
349 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
350 $defaults['option_type'] = 1;
353 if ($this->_action
& CRM_Core_Action
::DELETE
) {
357 // set soft credit defaults
358 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
361 $config = CRM_Core_Config
::singleton();
362 // set default country from config if no country set
363 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
364 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
367 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
368 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
371 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
372 $defaults = array_merge($defaults, $billingDefaults);
376 $this->_contactID
= $defaults['contact_id'];
379 // Set $newCredit variable in template to control whether link to credit card mode is included
380 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
382 // fix the display of the monetary value, CRM-4038
383 if (isset($defaults['total_amount'])) {
384 if (!empty($defaults['tax_amount'])) {
385 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
386 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
387 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
391 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
395 if (isset($defaults['non_deductible_amount'])) {
396 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
399 if (isset($defaults['fee_amount'])) {
400 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
403 if (isset($defaults['net_amount'])) {
404 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
407 if ($this->_contributionType
) {
408 $defaults['financial_type_id'] = $this->_contributionType
;
411 if (empty($defaults['payment_instrument_id'])) {
412 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
415 if (!empty($defaults['is_test'])) {
416 $this->assign('is_test', TRUE);
419 $this->assign('showOption', TRUE);
420 // for Premium section
421 if ($this->_premiumID
) {
422 $this->assign('showOption', FALSE);
423 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
425 $this->assign('showOption', TRUE);
427 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
429 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
432 $defaults['product_name'] = array($this->_productDAO
->product_id
);
434 if ($this->_productDAO
->fulfilled_date
) {
435 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
439 if (isset($this->userEmail
)) {
440 $this->assign('email', $this->userEmail
);
443 if (!empty($defaults['is_pay_later'])) {
444 $this->assign('is_pay_later', TRUE);
446 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
448 $dates = array('receive_date', 'receipt_date', 'cancel_date', 'thankyou_date');
449 foreach ($dates as $key) {
450 if (!empty($defaults[$key])) {
451 list($defaults[$key],
452 $defaults[$key . '_time']
453 ) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults),
459 if (!$this->_id
&& empty($defaults['receive_date'])) {
460 list($defaults['receive_date'],
461 $defaults['receive_date_time']
462 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
465 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
466 CRM_Utils_Array
::value('receive_date_time', $defaults)
468 $currency = CRM_Utils_Array
::value('currency', $defaults);
469 $this->assign('currency', $currency);
470 // Hack to get currency info to the js layer. CRM-11440
471 CRM_Utils_Money
::format(1);
472 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
473 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
475 //inherit campaign from pledge.
476 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
477 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
480 $this->_defaults
= $defaults;
485 * Build the form object
489 public function buildQuickForm() {
490 //@todo document the purpose of cdType (if still in use)
491 if ($this->_cdType
) {
492 CRM_Custom_Form_CustomData
::buildQuickForm($this);
496 //tax rate from financialType
497 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
498 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
500 // build price set form.
501 $buildPriceSet = FALSE;
502 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
503 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
504 $this->assign('invoicing', $invoicing);
506 // display tax amount on edit contribution page
507 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
508 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
511 if (empty($this->_lineItems
) &&
512 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
514 $buildPriceSet = TRUE;
515 $getOnlyPriceSetElements = TRUE;
516 if (!$this->_priceSetId
) {
517 $this->_priceSetId
= $_POST['price_set_id'];
518 $getOnlyPriceSetElements = FALSE;
521 $this->set('priceSetId', $this->_priceSetId
);
522 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
524 // get only price set form elements.
525 if ($getOnlyPriceSetElements) {
529 // use to build form during form rule.
530 $this->assign('buildPriceSet', $buildPriceSet);
532 $showAdditionalInfo = FALSE;
534 $defaults = $this->_values
;
535 $additionalDetailFields = array(
539 'non_deductible_amount',
543 foreach ($additionalDetailFields as $key) {
544 if (!empty($defaults[$key])) {
545 $defaults['hidden_AdditionalDetail'] = 1;
550 if ($this->_productDAO
) {
551 if ($this->_productDAO
->product_id
) {
552 $defaults['hidden_Premium'] = 1;
556 if ($this->_noteID
&&
557 isset($this->_values
['note'])
559 $defaults['hidden_AdditionalDetail'] = 1;
563 ts('Additional Details') => 'AdditionalDetail',
566 //Add Premium pane only if Premium is exists.
567 $dao = new CRM_Contribute_DAO_Product();
570 if ($dao->find(TRUE)) {
571 $paneNames[ts('Premium Information')] = 'Premium';
575 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
576 $buildRecurBlock = TRUE;
577 foreach ($this->billingPane
as $name => $label) {
578 if (!empty($this->billingFieldSets
[$name]['fields'])) {
579 //@todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
580 $paneNames[$label] = CRM_Utils_String
::convertStringToCamel($name);
586 foreach ($paneNames as $name => $type) {
587 $urlParams = "snippet=4&formType={$type}";
589 $urlParams .= "&mode={$this->_mode}";
593 if ($type == 'CreditCard' ||
594 $type == 'DirectDebit'
599 $allPanes[$name] = array(
600 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
605 // see if we need to include this paneName in the current form
606 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
607 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
609 $showAdditionalInfo = TRUE;
610 $allPanes[$name]['open'] = 'true';
613 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
614 //@todo would be good to align tpl name with form name...
615 $this->add('hidden', 'hidden_' . $type, 1);
618 $additionalInfoFormFunction = 'build' . $type;
619 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
622 if (empty($this->_recurPaymentProcessors
)) {
623 $buildRecurBlock = FALSE;
625 if ($buildRecurBlock) {
626 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
627 $this->setDefaults(array('is_recur' => 0));
629 $this->assign('buildRecurBlock', $buildRecurBlock);
630 $qfKey = $this->controller
->_key
;
631 $this->assign('qfKey', $qfKey);
632 $this->assign('allPanes', $allPanes);
633 $this->assign('showAdditionalInfo', $showAdditionalInfo);
635 if ($this->_formType
) {
636 $this->assign('formType', $this->_formType
);
640 $this->applyFilter('__ALL__', 'trim');
642 if ($this->_action
& CRM_Core_Action
::DELETE
) {
643 $this->addButtons(array(
646 'name' => ts('Delete'),
647 'spacing' => ' ',
652 'name' => ts('Cancel'),
659 //need to assign custom data type and subtype to the template
660 $this->assign('customDataType', 'Contribution');
661 $this->assign('customDataSubType', $this->_contributionType
);
662 $this->assign('entityID', $this->_id
);
664 if ($this->_context
== 'standalone') {
665 $this->addEntityRef('contact_id', ts('Contact'), array(
667 'api' => array('extra' => array('email')),
671 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
673 $financialType = $this->add('select', 'financial_type_id',
674 ts('Financial Type'),
675 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
677 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
679 $paymentInstrument = FALSE;
681 $paymentInstrument = $this->add('select', 'payment_instrument_id',
683 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
684 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
688 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
690 //add receipt for offline contribution
691 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
693 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
695 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
697 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
698 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
705 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
708 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
709 $suppressFlag = FALSE;
711 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
712 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
713 $suppressFlag = TRUE;
716 if (!$suppressFlag) {
721 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
725 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
730 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
731 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
736 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
737 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
738 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
743 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
754 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
760 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
763 $this->add('select', 'contribution_status_id',
764 ts('Contribution Status'),
770 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
772 if ($this->_online
) {
773 $this->assign('hideCalender', TRUE);
775 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
777 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
778 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
780 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
783 if ($buildRecurBlock) {
784 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
786 $element = $this->add('select',
787 'payment_processor_id',
788 ts('Payment Processor'),
794 if ($this->_online
) {
798 if (empty($this->_lineItems
)) {
799 $buildPriceSet = FALSE;
800 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
801 if (!empty($priceSets) && !$this->_ppID
) {
802 $buildPriceSet = TRUE;
805 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
806 // and if we already have line items for that participant. CRM-5095
807 if ($buildPriceSet && $this->_id
) {
808 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
809 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
814 if ($pledgePaymentId) {
815 $buildPriceSet = FALSE;
817 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
818 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
819 if (!CRM_Utils_System
::isNull($participantLI)) {
820 $buildPriceSet = FALSE;
825 $hasPriceSets = FALSE;
826 if ($buildPriceSet) {
827 $hasPriceSets = TRUE;
828 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
830 '' => ts('Choose price set'),
832 NULL, array('onchange' => "buildAmount( this.value );")
834 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
838 $this->assign('hasPriceSets', $hasPriceSets);
839 $currencyFreeze = FALSE;
840 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
841 if ($this->_online ||
$this->_ppID
) {
842 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
844 'style' => "background-color:#EBECE4",
846 $optionTypes = array(
847 '1' => ts('Adjust Pledge Payment Schedule?'),
848 '2' => ts('Adjust Total Pledge Amount?'),
850 $this->addRadio('option_type',
856 $currencyFreeze = TRUE;
860 $totalAmount = $this->addMoney('total_amount',
862 ($hasPriceSets) ?
FALSE : TRUE,
863 $attributes['total_amount'],
864 TRUE, 'currency', NULL, $currencyFreeze
868 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
870 //CRM-7362 --add campaigns.
871 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
873 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
877 $js = array('onclick' => "return verify( );");
880 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
883 $this->assign('outBound_option', $mailingInfo['outBound_option']);
885 $this->addButtons(array(
888 'name' => ts('Save'),
894 'name' => ts('Save and New'),
900 'name' => ts('Cancel'),
905 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
906 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
907 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
909 $totalAmount->freeze();
911 $checkNumber->freeze();
912 $paymentInstrument->freeze();
914 $financialType->freeze();
917 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
919 // if contribution is related to membership or participant freeze Financial Type, Amount
920 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
921 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
922 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
924 $totalAmount->freeze();
926 $financialType->freeze();
927 $this->assign('freezeFinancialType', TRUE);
931 if ($this->_action
& CRM_Core_Action
::VIEW
) {
939 * @param array $fields
940 * The input form values.
941 * @param array $files
942 * The uploaded files if any.
947 * true if no errors, else array of errors
949 public static function formRule($fields, $files, $self) {
952 //check for Credit Card Contribution.
954 if (empty($fields['payment_processor_id'])) {
955 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
959 // do the amount validations.
960 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
961 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
962 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
966 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
968 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
969 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
970 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
971 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
974 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
975 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
976 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
979 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
980 if (!empty($fields['fee_amount']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
981 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
984 // $trxn_id must be unique CRM-13919
985 if (!empty($fields['trxn_id'])) {
986 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
987 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
989 $queryParams[2] = array((int) $self->_id
, 'Integer');
990 $query .= ' and id !=%2';
992 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
994 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
998 $errors = array_merge($errors, $softErrors);
1003 * Process the form submission
1008 public function postProcess() {
1009 $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
1010 $softParams = $softIDs = array();
1012 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1013 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1014 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1015 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1020 // get the submitted form values.
1021 $submittedValues = $this->controller
->exportValues($this->_name
);
1022 if (!empty($submittedValues['price_set_id']) && $this->_action
& CRM_Core_Action
::UPDATE
) {
1023 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1024 $lineID = key($line);
1025 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1026 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1028 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1032 // process price set and get total amount and line items.
1033 $lineItem = array();
1034 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1035 if (empty($priceSetId) && !$this->_id
) {
1036 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1037 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1038 $fieldID = key($this->_priceSet
['fields']);
1039 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1040 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1041 $submittedValues['price_' . $fieldID] = 1;
1045 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1046 $submittedValues, $lineItem[$priceSetId]);
1048 // unset tax amount for offline 'is_quick_config' contribution
1049 if ($this->_priceSet
['is_quick_config'] &&
1050 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1052 unset($submittedValues['tax_amount']);
1054 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1057 if ($this->_compId
) {
1058 if ($this->_context
== 'participant') {
1059 $pId = $this->_compId
;
1061 elseif ($this->_context
== 'membership') {
1062 $isRelatedId = TRUE;
1065 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1069 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1070 if (array_key_exists('membership', $contributionDetails)) {
1071 $isRelatedId = TRUE;
1073 elseif (array_key_exists('participant', $contributionDetails)) {
1074 $pId = current($contributionDetails['participant']);
1080 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1084 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1085 // 10117 update th line items for participants
1087 $entityTable = 'participant';
1089 $isRelatedId = FALSE;
1090 $participantParams = array(
1091 'fee_amount' => $submittedValues['total_amount'],
1094 CRM_Event_BAO_Participant
::add($participantParams);
1095 if (empty($this->_lineItems
)) {
1096 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1100 $entityTable = 'contribution';
1101 $entityID = $this->_id
;
1104 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, $isQuickConfig, $isRelatedId);
1105 foreach (array_keys($lineItems) as $id) {
1106 $lineItems[$id]['id'] = $id;
1108 $itemId = key($lineItems);
1109 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1110 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1113 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1114 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1116 // Update line total and total amount with tax on edit
1117 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1118 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1119 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1122 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1123 $submittedValues['tax_amount'] = 'null';
1125 if ($lineItems[$itemId]['tax_rate']) {
1126 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1127 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1128 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1131 // 10117 update th line items for participants
1132 if (!empty($lineItems[$itemId]['price_field_id'])) {
1133 $lineItem[$this->_priceSetId
] = $lineItems;
1137 //CRM-11529 for quick config back office transactions
1138 //when financial_type_id is passed in form, update the
1139 //line items with the financial type selected in form
1140 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1142 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1143 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1147 if (!isset($submittedValues['total_amount'])) {
1148 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1150 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1152 if (!empty($submittedValues['pcp_made_through_id'])) {
1155 'pcp_made_through_id',
1156 'pcp_display_in_roll',
1157 'pcp_roll_nickname',
1158 'pcp_personal_note',
1160 foreach ($fields as $f) {
1161 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1165 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1166 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1167 //Delete existing soft credit records if soft credit list is empty on update
1168 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1171 //build soft credit params
1172 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1173 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1174 $softParams[$key]['contact_id'] = $val;
1175 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1176 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1177 if (!empty($submittedValues['soft_credit_id'][$key])) {
1178 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1184 // set the contact, when contact is selected
1185 if (!empty($submittedValues['contact_id'])) {
1186 $this->_contactID
= $submittedValues['contact_id'];
1189 $config = CRM_Core_Config
::singleton();
1191 //Credit Card Contribution.
1193 $session = CRM_Core_Session
::singleton();
1194 $this->processCreditCard($submittedValues, $config, $session, $lineItem);
1197 //Offline Contribution.
1198 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1200 // get the required field value only.
1201 $formValues = $submittedValues;
1202 $params = $ids = array();
1204 $params['contact_id'] = $this->_contactID
;
1206 $params['currency'] = $this->getCurrency($submittedValues);
1209 'financial_type_id',
1210 'contribution_status_id',
1211 'payment_instrument_id',
1216 foreach ($fields as $f) {
1217 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1221 $params['pcp'] = $pcp;
1223 if (!empty($softParams)) {
1224 $params['soft_credit'] = $softParams;
1225 $params['soft_credit_ids'] = $softIDs;
1228 //if priceset is used, no need to cleanup money
1231 $params['skipCleanMoney'] = 1;
1240 foreach ($dates as $d) {
1241 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1244 if (!empty($formValues['is_email_receipt'])) {
1245 $params['receipt_date'] = date("Y-m-d");
1248 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1249 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1251 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1252 $params['cancel_date'] = date('Y-m-d');
1256 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1259 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1260 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1261 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1262 $params['is_pay_later'] = 1;
1264 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1265 $params['is_pay_later'] = 0;
1268 $ids['contribution'] = $params['id'] = $this->_id
;
1270 //Add Additional common information to formatted params
1271 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1273 $params['contribution_mode'] = 'participant';
1274 $params['participant_id'] = $pId;
1275 $params['skipLineItem'] = 1;
1277 elseif ($isRelatedId) {
1278 $params['contribution_mode'] = 'membership';
1280 $params['line_item'] = $lineItem;
1281 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1282 if (isset($submittedValues['tax_amount'])) {
1283 $params['tax_amount'] = $submittedValues['tax_amount'];
1285 //create contribution.
1286 if ($isQuickConfig) {
1287 $params['is_quick_config'] = 1;
1291 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1292 // if non_deductible_amount does NOT exist - then calculate it depending on:
1293 // $ContributionType->is_deductible and whether there is a product (premium).
1294 if (empty($params['non_deductible_amount'])) {
1295 $contributionType = new CRM_Financial_DAO_FinancialType();
1296 $contributionType->id
= $params['financial_type_id'];
1297 if (!$contributionType->find(TRUE)) {
1298 CRM_Core_Error
::fatal('Could not find a system table');
1300 if ($contributionType->is_deductible
) {
1302 if (isset($formValues['product_name'][0])) {
1303 $selectProduct = $formValues['product_name'][0];
1305 // if there is a product - compare the value to the contribution amount
1306 if (isset($selectProduct)) {
1307 $productDAO = new CRM_Contribute_DAO_Product();
1308 $productDAO->id
= $selectProduct;
1309 $productDAO->find(TRUE);
1310 // product value exceeds contribution amount
1311 if ($params['total_amount'] < $productDAO->price
) {
1312 $params['non_deductible_amount'] = $params['total_amount'];
1314 // product value does NOT exceed contribution amount
1316 $params['non_deductible_amount'] = $productDAO->price
;
1319 // contribution is deductible - but there is no product
1321 $params['non_deductible_amount'] = '0.00';
1324 // contribution is NOT deductible
1326 $params['non_deductible_amount'] = $params['total_amount'];
1330 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1332 // process associated membership / participant, CRM-4395
1333 $relatedComponentStatusMsg = NULL;
1334 if ($contribution->id
&& $this->_action
& CRM_Core_Action
::UPDATE
) {
1335 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1336 $contribution->contribution_status_id
,
1337 CRM_Utils_Array
::value('contribution_status_id',
1344 if ($contribution->id
&& isset($formValues['note'])) {
1345 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1349 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1350 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1351 $this->_premiumID
, $this->_options
1355 // assign tax calculation for contribution receipts
1357 $getTaxDetails = FALSE;
1358 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1359 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1361 if ($this->_action
& CRM_Core_Action
::ADD
) {
1364 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
1365 $line = $this->_lineItems
;
1367 foreach ($line as $key => $value) {
1368 foreach ($value as $v) {
1369 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1370 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1373 if (isset($v['tax_rate'])) {
1374 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1375 $getTaxDetails = TRUE;
1383 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1384 if (isset($submittedValues['tax_amount'])) {
1385 $totalTaxAmount = $submittedValues['tax_amount'];
1388 $totalTaxAmount = $this->_values
['tax_amount'];
1390 $this->assign('totalTaxAmount', $totalTaxAmount);
1391 $this->assign('dataArray', $taxRate);
1394 if (CRM_Utils_Array
::value('price_set_id', $submittedValues)) {
1395 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1396 $this->assign('getTaxDetails', $getTaxDetails);
1397 $this->assign('dataArray', $taxRate);
1398 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1401 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1406 //send receipt mail.
1407 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1408 $formValues['contact_id'] = $this->_contactID
;
1409 $formValues['contribution_id'] = $contribution->id
;
1411 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1413 // to get 'from email id' for send receipt
1414 $this->fromEmailId
= $formValues['from_email_address'];
1415 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues);
1418 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1424 //update pledge payment status.
1425 if ((($this->_ppID
&& $contribution->id
) && $this->_action
& CRM_Core_Action
::ADD
) ||
1426 (($pledgePaymentId) && $this->_action
& CRM_Core_Action
::UPDATE
)
1430 //store contribution id in payment record.
1431 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1434 $this->_ppID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1439 $this->_pledgeID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1446 $adjustTotalAmount = FALSE;
1447 if (CRM_Utils_Array
::value('option_type', $formValues) == 2) {
1448 $adjustTotalAmount = TRUE;
1451 $updatePledgePaymentStatus = FALSE;
1452 //do only if either the status or the amount has changed
1453 if ($this->_action
& CRM_Core_Action
::ADD
) {
1454 $updatePledgePaymentStatus = TRUE;
1456 elseif ($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $formValues['contribution_status_id']) ||
1457 ($this->_defaults
['total_amount'] != $formValues['total_amount']))
1459 $updatePledgePaymentStatus = TRUE;
1462 if ($updatePledgePaymentStatus) {
1463 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1464 array($this->_ppID
),
1465 $contribution->contribution_status_id
,
1467 $contribution->total_amount
,
1473 $statusMsg = ts('The contribution record has been saved.');
1474 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1475 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1478 if ($relatedComponentStatusMsg) {
1479 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1482 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1483 //Offline Contribution ends.
1485 $session = CRM_Core_Session
::singleton();
1486 $buttonName = $this->controller
->getButtonName();
1487 if ($this->_context
== 'standalone') {
1488 if ($buttonName == $this->getButtonName('upload', 'new')) {
1489 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1490 'reset=1&action=add&context=standalone'
1494 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1495 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1499 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1500 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1501 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1504 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1505 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1506 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1510 //store contribution ID if not yet set (on create)
1511 if (empty($this->_id
) && !empty($contribution->id
)) {
1512 $this->_id
= $contribution->id
;
1517 * @param $submittedValues
1519 * @param CRM_Core_Session $session
1522 * @throws CRM_Core_Exception
1524 public function processCreditCard($submittedValues, $config, $session, $lineItem) {
1525 $sendReceipt = $contribution = FALSE;
1527 $unsetParams = array(
1529 'payment_instrument_id',
1530 'contribution_status_id',
1534 foreach ($unsetParams as $key) {
1535 if (isset($submittedValues[$key])) {
1536 unset($submittedValues[$key]);
1539 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1540 // CRM-12680 set $_lineItem if its not set
1541 if (empty($this->_lineItem
) && !empty($lineItem)) {
1542 $this->_lineItem
= $lineItem;
1545 //Get the require fields value only.
1546 $params = $this->_params
= $submittedValues;
1548 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1552 //get the payment processor id as per mode.
1553 $this->_params
['payment_processor'] = $params['payment_processor_id']
1554 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1556 $now = date('YmdHis');
1559 // we need to retrieve email address
1560 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1561 list($this->userDisplayName
,
1563 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1564 $this->assign('displayName', $this->userDisplayName
);
1567 //set email for primary location.
1568 $fields['email-Primary'] = 1;
1569 $params['email-Primary'] = $this->userEmail
;
1571 // now set the values for the billing location.
1572 foreach (array_keys($this->_fields
) as $name) {
1576 // also add location name to the array
1577 $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);
1579 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1580 $fields["address_name-{$this->_bltID}"] = 1;
1581 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1586 $nameFields = array('first_name', 'middle_name', 'last_name');
1587 foreach ($nameFields as $name) {
1589 if (array_key_exists("billing_$name", $params)) {
1590 $params[$name] = $params["billing_{$name}"];
1591 $params['preserveDBName'] = TRUE;
1595 if (!empty($params['source'])) {
1596 unset($params['source']);
1598 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1604 // add all the additional payment params we need
1605 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1606 $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}"]);
1608 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1609 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1611 $legacyCreditCardExpiryCheck = FALSE;
1612 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1613 $legacyCreditCardExpiryCheck = TRUE;
1615 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1616 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1617 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1619 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1620 $this->_params
['amount'] = $this->_params
['total_amount'];
1621 $this->_params
['amount_level'] = 0;
1622 $this->_params
['description'] = ts('Office Credit Card contribution');
1623 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1625 $config->defaultCurrency
1627 $this->_params
['payment_action'] = 'Sale';
1628 if (!empty($this->_params
['receive_date'])) {
1629 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1632 if (!empty($params['soft_credit_to'])) {
1633 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1634 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1637 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1638 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1639 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1641 //Add common data to formatted params
1642 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1644 if (empty($this->_params
['invoice_id'])) {
1645 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1648 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1651 // at this point we've created a contact and stored its address etc
1652 // all the payment processors expect the name and address to be in the
1653 // so we copy stuff over to first_name etc.
1654 $paymentParams = $this->_params
;
1655 $paymentParams['contactID'] = $this->_contactID
;
1656 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1658 $contributionType = new CRM_Financial_DAO_FinancialType();
1659 $contributionType->id
= $params['financial_type_id'];
1661 // add some financial type details to the params list
1662 // if folks need to use it
1663 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1664 $paymentParams['contributionPageID'] = NULL;
1666 if (!empty($this->_params
['is_email_receipt'])) {
1667 $paymentParams['email'] = $this->userEmail
;
1668 $paymentParams['is_email_receipt'] = 1;
1671 $paymentParams['is_email_receipt'] = 0;
1672 $this->_params
['is_email_receipt'] = 0;
1674 if (!empty($this->_params
['receive_date'])) {
1675 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1678 // For recurring contribution, create Contribution Record first.
1679 // Contribution ID, Recurring ID and Contact ID needed
1680 // When we get a callback from the payment processor, CRM-7115
1682 if (!empty($paymentParams['is_recur'])) {
1683 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1693 $paymentParams['contributionID'] = $contribution->id
;
1694 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1695 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1696 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1699 if ($paymentParams['amount'] > 0.0) {
1700 // force a re-get of the payment processor in case the form changed it, CRM-7179
1701 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1703 $result = $payment->doPayment($paymentParams, 'contribute');
1705 catch (CRM_Core_Exception
$e) {
1706 $message = ts("Payment Processor Error message") . $e->getMessage();
1707 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1708 //set the contribution mode.
1709 $urlParams = "action=add&cid={$this->_contactID}";
1711 $urlParams .= "&mode={$this->_mode}";
1713 if (!empty($this->_ppID
)) {
1714 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1716 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1720 $this->_params
= array_merge($this->_params
, $result);
1722 $this->_params
['receive_date'] = $now;
1724 if (!empty($this->_params
['is_email_receipt'])) {
1725 $this->_params
['receipt_date'] = $now;
1728 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1729 $params['receipt_date_time'], TRUE
1733 $this->set('params', $this->_params
);
1734 $this->assign('trxn_id', $result['trxn_id']);
1735 $this->assign('receive_date', $this->_params
['receive_date']);
1737 // result has all the stuff we need
1738 // lets archive it to a financial transaction
1739 if ($contributionType->is_deductible
) {
1740 $this->assign('is_deductible', TRUE);
1741 $this->set('is_deductible', TRUE);
1744 // set source if not set
1745 if (empty($this->_params
['source'])) {
1746 $userID = $session->get('userID');
1747 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1750 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1753 // build custom data getFields array
1754 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1755 CRM_Utils_Array
::value('financial_type_id', $params)
1757 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1758 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1760 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1765 if (empty($paymentParams['is_recur'])) {
1766 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1777 //send receipt mail.
1778 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1779 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1780 $this->_params
['contact_id'] = $this->_contactID
;
1781 $this->_params
['contribution_id'] = $contribution->id
;
1782 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1786 if ($contribution->id
&& isset($params['note'])) {
1787 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1790 if ($contribution->id
&& isset($params['product_name'][0])) {
1791 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1794 //update pledge payment status.
1795 if ($this->_ppID
&& $contribution->id
) {
1796 //store contribution id in payment record.
1797 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1799 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1800 array($this->_ppID
),
1801 $contribution->contribution_status_id
,
1803 $contribution->total_amount
1807 if ($contribution->id
) {
1808 $statusMsg = ts('The contribution record has been processed.');
1809 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1810 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1812 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1817 * @param array $paymentParams
1820 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1821 //make sure to cleanup db for recurring case.
1822 if (!empty($paymentParams['contributionID'])) {
1823 CRM_Core_Error
::debug_log_message($message .
1824 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1825 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1827 if (!empty($paymentParams['contributionRecurID'])) {
1828 CRM_Core_Error
::debug_log_message($message .
1829 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1830 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);