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 * logged in user's email
200 * Price set as an array
207 * @todo can we define this a as protected? can we define higher up the chain
217 public $userDisplayName;
219 * Function to set variables up before form is built
224 public function preProcess() {
226 //check permission for action.
227 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
228 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
231 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
233 $this->assign('cdType', FALSE);
234 if ($this->_cdType
) {
235 $this->assign('cdType', TRUE);
236 CRM_Custom_Form_CustomData
::preProcess($this);
240 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
243 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId
);
245 $this->assign('priceSetId', $this->_priceSetId
);
247 //get the pledge payment id
248 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
251 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
254 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
255 $this->assign('action', $this->_action
);
257 //get the contribution id if update
258 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
259 if (!empty($this->_id
)) {
260 $this->assign('contribID', $this->_id
);
263 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
264 $this->assign('context', $this->_context
);
266 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
268 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
270 //set the contribution mode.
271 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
273 $this->assign('contributionMode', $this->_mode
);
275 $this->_paymentProcessor
= array('billing_mode' => 1);
277 $this->assign('showCheckNumber', TRUE);
279 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
280 $this->assignProcessors();
282 if ($this->_contactID
) {
283 list($this->userDisplayName
, $this->userEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
284 $this->assign('displayName', $this->userDisplayName
);
287 // also check for billing information
288 // get the billing location type
289 $this->assignBillingType();
291 $this->_fields
= array();
293 CRM_Core_Payment_Form
::setPaymentFieldsByType(CRM_Utils_Array
::value('payment_type', $this->_processors
), $this);
295 if ($this->_action
& CRM_Core_Action
::DELETE
) {
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);
328 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
331 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
334 if ($this->_contactID
) {
335 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactID
);
337 // Check if this is default domain contact CRM-10482
338 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactID
)) {
339 $displayName .= ' (' . ts('default organization') . ')';
342 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
343 CRM_Utils_System
::setTitle(ts('Contribution from') . ' ' . $displayName);
347 CRM_Contribute_Form_SoftCredit
::preprocess($this);
351 function setDefaultValues() {
352 if ($this->_cdType
) {
353 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
356 $defaults = $this->_values
;
358 //set defaults for pledge payment.
360 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
361 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
362 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
363 $defaults['option_type'] = 1;
366 if ($this->_action
& CRM_Core_Action
::DELETE
) {
370 // set soft credit defaults
371 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
374 $config = CRM_Core_Config
::singleton();
375 // set default country from config if no country set
376 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
377 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
380 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
381 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
384 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
385 $defaults = array_merge($defaults, $billingDefaults);
387 // now fix all state country selectors, set correct state based on country
388 CRM_Core_BAO_Address
::fixAllStateSelects($this, $defaults);
392 $this->_contactID
= $defaults['contact_id'];
395 // Set $newCredit variable in template to control whether link to credit card mode is included
396 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
398 // fix the display of the monetary value, CRM-4038
399 if (isset($defaults['total_amount'])) {
400 $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 if ($this->_cdType
) {
500 CRM_Custom_Form_CustomData
::buildQuickForm($this);
505 // build price set form.
506 $buildPriceSet = FALSE;
507 if (empty($this->_lineItems
) &&
508 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
510 $buildPriceSet = TRUE;
511 $getOnlyPriceSetElements = TRUE;
512 if (!$this->_priceSetId
) {
513 $this->_priceSetId
= $_POST['price_set_id'];
514 $getOnlyPriceSetElements = FALSE;
517 $this->set('priceSetId', $this->_priceSetId
);
518 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
520 // get only price set form elements.
521 if ($getOnlyPriceSetElements) {
525 // use to build form during form rule.
526 $this->assign('buildPriceSet', $buildPriceSet);
528 $showAdditionalInfo = FALSE;
530 $defaults = $this->_values
;
531 $additionalDetailFields = array(
535 'non_deductible_amount',
539 foreach ($additionalDetailFields as $key) {
540 if (!empty($defaults[$key])) {
541 $defaults['hidden_AdditionalDetail'] = 1;
546 if ($this->_productDAO
) {
547 if ($this->_productDAO
->product_id
) {
548 $defaults['hidden_Premium'] = 1;
552 if ($this->_noteID
&&
553 isset($this->_values
['note'])
555 $defaults['hidden_AdditionalDetail'] = 1;
559 ts('Additional Details') => 'AdditionalDetail',
562 //Add Premium pane only if Premium is exists.
563 $dao = new CRM_Contribute_DAO_Product();
566 if ($dao->find(TRUE)) {
567 $paneNames[ts('Premium Information')] = 'Premium';
572 if (CRM_Utils_Array
::value('payment_type', $this->_processors
) & CRM_Core_Payment
::PAYMENT_TYPE_DIRECT_DEBIT
574 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
577 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
580 if (is_array($ccPane)) {
581 $paneNames = array_merge($ccPane, $paneNames);
584 $buildRecurBlock = FALSE;
585 foreach ($paneNames as $name => $type) {
586 $urlParams = "snippet=4&formType={$type}";
588 $urlParams .= "&mode={$this->_mode}";
592 if ($type == 'CreditCard' ||
593 $type == 'DirectDebit'
598 $allPanes[$name] = array(
599 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
604 // see if we need to include this paneName in the current form
605 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
606 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
608 $showAdditionalInfo = TRUE;
609 $allPanes[$name]['open'] = 'true';
612 if ($type == 'CreditCard') {
613 $buildRecurBlock = TRUE;
614 $this->add('hidden', 'hidden_CreditCard', 1);
615 CRM_Core_Payment_Form
::buildCreditCard($this, TRUE);
617 elseif ($type == 'DirectDebit') {
618 $buildRecurBlock = TRUE;
619 $this->add('hidden', 'hidden_DirectDebit', 1);
620 CRM_Core_Payment_Form
::buildDirectDebit($this, TRUE);
623 $additionalInfoFormFunction = 'build' . $type;
624 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
627 if (empty($this->_recurPaymentProcessors
)) {
628 $buildRecurBlock = FALSE;
630 if ($buildRecurBlock) {
631 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
632 $this->setDefaults(array('is_recur' => 0));
634 $this->assign('buildRecurBlock', $buildRecurBlock);
635 $qfKey = $this->controller
->_key
;
636 $this->assign('qfKey', $qfKey);
637 $this->assign('allPanes', $allPanes);
638 $this->assign('showAdditionalInfo', $showAdditionalInfo);
640 if ($this->_formType
) {
641 $this->assign('formType', $this->_formType
);
645 $this->applyFilter('__ALL__', 'trim');
647 if ($this->_action
& CRM_Core_Action
::DELETE
) {
648 $this->addButtons(array(
651 'name' => ts('Delete'),
652 'spacing' => ' ',
657 'name' => ts('Cancel')
664 //need to assign custom data type and subtype to the template
665 $this->assign('customDataType', 'Contribution');
666 $this->assign('customDataSubType', $this->_contributionType
);
667 $this->assign('entityID', $this->_id
);
669 if ($this->_context
== 'standalone') {
670 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
673 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
675 $financialType = $this->add('select', 'financial_type_id',
676 ts('Financial Type'),
677 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
679 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
681 $paymentInstrument = FALSE;
683 $paymentInstrument = $this->add('select', 'payment_instrument_id',
685 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
686 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
690 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']);
692 //add receipt for offline contribution
693 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
695 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
697 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
699 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
700 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
707 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
710 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
711 $suppressFlag = FALSE;
713 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
714 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
715 $suppressFlag = TRUE;
718 if (!$suppressFlag) {
723 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
727 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
732 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
733 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
738 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
739 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
740 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
744 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 ($this->_action
& CRM_Core_Action
::VIEW
) {
927 * @param array $fields the input form values
928 * @param array $files the uploaded files if any
931 * @internal param array $options additional user data
933 * @return true if no errors, else array of errors
937 static function formRule($fields, $files, $self) {
940 //check for Credit Card Contribution.
942 if (empty($fields['payment_processor_id'])) {
943 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
947 // do the amount validations.
948 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
949 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
950 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
954 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
956 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
957 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
958 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
959 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
962 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
963 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
964 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
967 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
968 if (!empty($fields['fee_amount']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
969 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
972 // $trxn_id must be unique CRM-13919
973 if (!empty($fields['trxn_id'])) {
974 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
975 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
977 $queryParams[2] = array((int)$self->_id
, 'Integer');
978 $query .= ' and id !=%2';
980 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
982 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
986 $errors = array_merge($errors, $softErrors);
991 * Function to process the form
997 public function postProcess() {
998 $session = CRM_Core_Session
::singleton();
999 $sendReceipt = $pId = $contribution = FALSE;
1000 $softParams = $softIDs =array();
1002 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1003 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1004 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1005 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1010 // get the submitted form values.
1011 $submittedValues = $this->controller
->exportValues($this->_name
);
1012 if (!empty($submittedValues['price_set_id']) && $this->_action
& CRM_Core_Action
::UPDATE
) {
1013 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1014 $lineID = key($line);
1015 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1016 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1018 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1022 // process price set and get total amount and line items.
1023 $lineItem = array();
1024 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1025 if (empty($priceSetId) && !$this->_id
) {
1026 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1027 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1028 $fieldID = key($this->_priceSet
['fields']);
1029 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1030 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1031 $submittedValues['price_' . $fieldID] = 1;
1035 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1036 $submittedValues, $lineItem[$priceSetId]);
1038 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1042 $pId = ($this->_compId
&& $this->_context
== 'participant') ?
$this->_compId
: CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1044 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1045 // 10117 update th line items for participants
1047 $entityTable = 'participant';
1049 $participantParams = array(
1050 'fee_amount' => $submittedValues['total_amount'],
1053 CRM_Event_BAO_Participant
::add($participantParams);
1054 if (empty($this->_lineItems
)) {
1055 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1059 $entityTable = 'contribution';
1060 $entityID = $this->_id
;
1063 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable);
1064 foreach (array_keys($lineItems) as $id) {
1065 $lineItems[$id]['id'] = $id;
1067 $itemId = key($lineItems);
1068 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1069 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1072 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1073 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1075 // 10117 update th line items for participants
1076 if (!empty($lineItems[$itemId]['price_field_id'])) {
1077 $lineItem[$this->_priceSetId
] = $lineItems;
1081 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1084 //CRM-11529 for quick config back office transactions
1085 //when financial_type_id is passed in form, update the
1086 //line items with the financial type selected in form
1087 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1089 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1090 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1094 if (!isset($submittedValues['total_amount'])) {
1095 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1097 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1099 if (!empty($submittedValues['pcp_made_through_id'])) {
1102 'pcp_made_through_id',
1103 'pcp_display_in_roll',
1104 'pcp_roll_nickname',
1105 'pcp_personal_note',
1107 foreach ($fields as $f) {
1108 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1112 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1113 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1114 //Delete existing soft credit records if soft credit list is empty on update
1115 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1118 //build soft credit params
1119 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1120 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1121 $softParams[$key]['contact_id'] = $val;
1122 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1123 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1124 if (!empty($submittedValues['soft_credit_id'][$key])) {
1125 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1131 // set the contact, when contact is selected
1132 if (!empty($submittedValues['contact_id'])) {
1133 $this->_contactID
= $submittedValues['contact_id'];
1136 $config = CRM_Core_Config
::singleton();
1138 //Credit Card Contribution.
1140 $this->processCreditCard($submittedValues, $config, $session, $lineItem);
1143 //Offline Contribution.
1144 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1146 // get the required field value only.
1147 $formValues = $submittedValues;
1148 $params = $ids = array();
1150 $params['contact_id'] = $this->_contactID
;
1152 $params['currency'] = $this->getCurrency($submittedValues);
1155 'financial_type_id',
1156 'contribution_status_id',
1157 'payment_instrument_id',
1162 foreach ($fields as $f) {
1163 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1167 $params['pcp'] = $pcp;
1169 if (!empty($softParams)) {
1170 $params['soft_credit'] = $softParams;
1171 $params['soft_credit_ids'] = $softIDs;
1174 //if priceset is used, no need to cleanup money
1177 $params['skipCleanMoney'] = 1;
1186 foreach ($dates as $d) {
1187 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1190 if (!empty($formValues['is_email_receipt'])) {
1191 $params['receipt_date'] = date("Y-m-d");
1194 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1195 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1197 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1198 $params['cancel_date'] = date('Y-m-d');
1202 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1205 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1206 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1207 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1208 $params['is_pay_later'] = 1;
1210 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1211 $params['is_pay_later'] = 0;
1214 $ids['contribution'] = $params['id'] = $this->_id
;
1216 //Add Additional common information to formatted params
1217 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1219 $params['contribution_mode'] = 'participant';
1220 $params['participant_id'] = $pId;
1221 $params['skipLineItem'] = 1;
1223 $params['line_item'] = $lineItem;
1224 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1225 //create contribution.
1226 if ($isQuickConfig) {
1227 $params['is_quick_config'] = 1;
1231 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1232 // if non_deductible_amount does NOT exist - then calculate it depending on:
1233 // $ContributionType->is_deductible and whether there is a product (premium).
1234 if (!isset($params['non_deductible_amount']) ||
(!empty($params['non_deductible_amount']))) {
1235 $contributionType = new CRM_Financial_DAO_FinancialType();
1236 $contributionType->id
= $params['financial_type_id'];
1237 if (!$contributionType->find(TRUE)) {
1238 CRM_Core_Error
::fatal('Could not find a system table');
1240 if ($contributionType->is_deductible
) {
1242 if (isset($formValues['product_name'][0])) {
1243 $selectProduct = $formValues['product_name'][0];
1245 // if there is a product - compare the value to the contribution amount
1246 if (isset($selectProduct)) {
1247 $productDAO = new CRM_Contribute_DAO_Product();
1248 $productDAO->id
= $selectProduct;
1249 $productDAO->find(TRUE);
1250 // product value exceeds contribution amount
1251 if ($params['total_amount'] < $productDAO->price
) {
1252 $params['non_deductible_amount'] = $params['total_amount'];
1254 // product value does NOT exceed contribution amount
1256 $params['non_deductible_amount'] = $productDAO->price
;
1259 // contribution is deductible - but there is no product
1261 $params['non_deductible_amount'] = '0.00';
1264 // contribution is NOT deductible
1266 $params['non_deductible_amount'] = $params['total_amount'];
1270 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1272 // process associated membership / participant, CRM-4395
1273 $relatedComponentStatusMsg = NULL;
1274 if ($contribution->id
&& $this->_action
& CRM_Core_Action
::UPDATE
) {
1275 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1276 $contribution->contribution_status_id
,
1277 CRM_Utils_Array
::value('contribution_status_id',
1284 if ($contribution->id
&& isset($formValues['note'])) {
1285 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1289 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1290 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1291 $this->_premiumID
, $this->_options
1295 //send receipt mail.
1296 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1297 $formValues['contact_id'] = $this->_contactID
;
1298 $formValues['contribution_id'] = $contribution->id
;
1300 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1302 // to get 'from email id' for send receipt
1303 $this->fromEmailId
= $formValues['from_email_address'];
1304 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues);
1307 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1313 //update pledge payment status.
1314 if ((($this->_ppID
&& $contribution->id
) && $this->_action
& CRM_Core_Action
::ADD
) ||
1315 (($pledgePaymentId) && $this->_action
& CRM_Core_Action
::UPDATE
)
1319 //store contribution id in payment record.
1320 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1323 $this->_ppID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1328 $this->_pledgeID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1335 $adjustTotalAmount = FALSE;
1336 if (CRM_Utils_Array
::value('option_type', $formValues) == 2) {
1337 $adjustTotalAmount = TRUE;
1340 $updatePledgePaymentStatus = FALSE;
1341 //do only if either the status or the amount has changed
1342 if ($this->_action
& CRM_Core_Action
::ADD
) {
1343 $updatePledgePaymentStatus = TRUE;
1345 elseif ($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $formValues['contribution_status_id']) ||
1346 ($this->_defaults
['total_amount'] != $formValues['total_amount']))
1348 $updatePledgePaymentStatus = TRUE;
1351 if ($updatePledgePaymentStatus) {
1352 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1353 array($this->_ppID
),
1354 $contribution->contribution_status_id
,
1356 $contribution->total_amount
,
1362 $statusMsg = ts('The contribution record has been saved.');
1363 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1364 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1367 if ($relatedComponentStatusMsg) {
1368 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1371 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1372 //Offline Contribution ends.
1374 $buttonName = $this->controller
->getButtonName();
1375 if ($this->_context
== 'standalone') {
1376 if ($buttonName == $this->getButtonName('upload', 'new')) {
1377 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1378 'reset=1&action=add&context=standalone'
1382 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1383 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1387 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1388 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1389 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1392 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1393 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1394 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1398 //store contribution ID if not yet set (on create)
1399 if ( empty($this->_id
) && !empty($contribution->id
) ) {
1400 $this->_id
= $contribution->id
;
1405 * @param $submittedValues
1407 * @param $session CRM_Core_Session
1410 * @throws CRM_Core_Exception
1412 public function processCreditCard($submittedValues, $config, $session, $lineItem) {
1413 $sendReceipt = $contribution = FALSE;
1414 $unsetParams = array(
1416 'payment_instrument_id',
1417 'contribution_status_id',
1421 foreach ($unsetParams as $key) {
1422 if (isset($submittedValues[$key])) {
1423 unset($submittedValues[$key]);
1426 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1427 // CRM-12680 set $_lineItem if its not set
1428 if (empty($this->_lineItem
) && !empty($lineItem)) {
1429 $this->_lineItem
= $lineItem;
1432 //Get the require fields value only.
1433 $params = $this->_params
= $submittedValues;
1435 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1439 //get the payment processor id as per mode.
1440 $this->_params
['payment_processor'] = $params['payment_processor_id'] =
1441 $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1443 $now = date('YmdHis');
1446 // we need to retrieve email address
1447 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1448 list($this->userDisplayName
,
1450 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1451 $this->assign('displayName', $this->userDisplayName
);
1454 //set email for primary location.
1455 $fields['email-Primary'] = 1;
1456 $params['email-Primary'] = $this->userEmail
;
1458 // now set the values for the billing location.
1459 foreach (array_keys($this->_fields
) as $name) {
1463 // also add location name to the array
1464 $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);
1465 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1466 $fields["address_name-{$this->_bltID}"] = 1;
1468 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1473 $nameFields = array('first_name', 'middle_name', 'last_name');
1474 foreach ($nameFields as $name) {
1476 if (array_key_exists("billing_$name", $params)) {
1477 $params[$name] = $params["billing_{$name}"];
1478 $params['preserveDBName'] = TRUE;
1482 if (!empty($params['source'])) {
1483 unset($params['source']);
1485 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1491 // add all the additional payment params we need
1492 $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}"]);
1493 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1495 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
) {
1496 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1497 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1499 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1500 $this->_params
['amount'] = $this->_params
['total_amount'];
1501 $this->_params
['amount_level'] = 0;
1502 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1504 $config->defaultCurrency
1506 $this->_params
['payment_action'] = 'Sale';
1507 if (!empty($this->_params
['receive_date'])) {
1508 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1511 if (!empty($params['soft_credit_to'])) {
1512 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1513 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1516 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1517 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1518 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1520 //Add common data to formatted params
1521 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1523 if (empty($this->_params
['invoice_id'])) {
1524 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1527 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1530 // at this point we've created a contact and stored its address etc
1531 // all the payment processors expect the name and address to be in the
1532 // so we copy stuff over to first_name etc.
1533 $paymentParams = $this->_params
;
1534 $paymentParams['contactID'] = $this->_contactID
;
1535 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1537 $contributionType = new CRM_Financial_DAO_FinancialType();
1538 $contributionType->id
= $params['financial_type_id'];
1539 if (!$contributionType->find(TRUE)) {
1540 CRM_Core_Error
::fatal('Could not find a system table');
1543 // add some financial type details to the params list
1544 // if folks need to use it
1545 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1546 $paymentParams['contributionPageID'] = NULL;
1547 if (!empty($this->_params
['is_email_receipt'])) {
1548 $paymentParams['email'] = $this->userEmail
;
1549 $paymentParams['is_email_receipt'] = 1;
1552 $paymentParams['is_email_receipt'] = 0;
1553 $this->_params
['is_email_receipt'] = 0;
1555 if (!empty($this->_params
['receive_date'])) {
1556 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1559 // For recurring contribution, create Contribution Record first.
1560 // Contribution ID, Recurring ID and Contact ID needed
1561 // When we get a callback from the payment processor, CRM-7115
1562 if (!empty($paymentParams['is_recur'])) {
1563 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1573 $paymentParams['contributionID'] = $contribution->id
;
1574 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1575 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1576 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1579 if ($paymentParams['amount'] > 0.0) {
1580 // force a re-get of the payment processor in case the form changed it, CRM-7179
1581 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1582 $result = $payment->doDirectPayment($paymentParams);
1585 if (is_a($result, 'CRM_Core_Error')) {
1586 //make sure to cleanup db for recurring case.
1587 if (!empty($paymentParams['contributionID'])) {
1588 CRM_Core_Error
::debug_log_message(CRM_Core_Error
::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1589 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1591 if (!empty($paymentParams['contributionRecurID'])) {
1592 CRM_Core_Error
::debug_log_message(CRM_Core_Error
::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1593 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1596 //set the contribution mode.
1597 $urlParams = "action=add&cid={$this->_contactID}";
1599 $urlParams .= "&mode={$this->_mode}";
1601 if (!empty($this->_ppID
)) {
1602 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1604 CRM_Core_Error
::displaySessionError($result);
1605 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams));
1609 $this->_params
= array_merge($this->_params
, $result);
1612 $this->_params
['receive_date'] = $now;
1614 if (!empty($this->_params
['is_email_receipt'])) {
1615 $this->_params
['receipt_date'] = $now;
1618 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1619 $params['receipt_date_time'], TRUE
1623 $this->set('params', $this->_params
);
1624 $this->assign('trxn_id', $result['trxn_id']);
1625 $this->assign('receive_date', $this->_params
['receive_date']);
1627 // result has all the stuff we need
1628 // lets archive it to a financial transaction
1629 if ($contributionType->is_deductible
) {
1630 $this->assign('is_deductible', TRUE);
1631 $this->set('is_deductible', TRUE);
1634 // set source if not set
1635 if (empty($this->_params
['source'])) {
1636 $userID = $session->get('userID');
1637 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1640 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1643 // build custom data getFields array
1644 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1645 CRM_Utils_Array
::value('financial_type_id', $params)
1647 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1648 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1650 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1657 if (empty($paymentParams['is_recur'])) {
1658 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1669 //send receipt mail.
1670 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1671 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1672 $this->_params
['contact_id'] = $this->_contactID
;
1673 $this->_params
['contribution_id'] = $contribution->id
;
1674 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1678 if ($contribution->id
&& isset($params['note'])) {
1679 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1682 if ($contribution->id
&& isset($params['product_name'][0])) {
1683 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1686 //update pledge payment status.
1687 if ($this->_ppID
&& $contribution->id
) {
1688 //store contribution id in payment record.
1689 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1691 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($this->_pledgeID
,
1692 array($this->_ppID
),
1693 $contribution->contribution_status_id
,
1695 $contribution->total_amount
1699 if ($contribution->id
) {
1700 $statusMsg = ts('The contribution record has been processed.');
1701 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1702 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1704 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');