3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for processing a contribution
20 * CRM-16229 - During the event registration bulk action via search we
21 * need to inherit CRM_Contact_Form_Task so that we can inherit functions
22 * like getContactIds and make use of controller state. But this is not possible
23 * because CRM_Event_Form_Participant inherits this class.
24 * Ideal situation would be something like
25 * CRM_Event_Form_Participant extends CRM_Contact_Form_Task,
26 * CRM_Contribute_Form_AbstractEditPayment
27 * However this is not possible. Currently PHP does not support multiple
28 * inheritance. So work around solution is to extend this class with
29 * CRM_Contact_Form_Task which further extends CRM_Core_Form.
32 class CRM_Contribute_Form_AbstractEditPayment
extends CRM_Contact_Form_Task
{
34 use CRM_Financial_Form_SalesTaxTrait
;
45 * Current payment processor including a copy of the object in 'object' key.
49 public $_paymentProcessor;
52 * Available recurring processors.
56 public $_recurPaymentProcessors = [];
59 * Array of processor options in the format id => array($id => $label)
60 * WARNING it appears that the format used to differ to this and there are places in the code that
61 * expect the old format. $this->_paymentProcessors provides the additional data which this
62 * array seems to have provided in the past
68 * Available payment processors with full details including the key 'object' indexed by their id
71 protected $_paymentProcessors = [];
74 * Instance of the payment processor object.
76 * @var CRM_Core_Payment
78 protected $_paymentObject;
81 * The id of the contribution that we are processing.
88 * Entity that $this->_id relates to.
90 * If set the contact id is not required in the url.
97 * The id of the premium that we are proceessing.
101 public $_premiumID = NULL;
104 * @var CRM_Contribute_DAO_ContributionProduct
106 public $_productDAO = NULL;
116 * The id of the contact associated with this contribution
123 * The id of the pledge payment that we are processing
130 * The id of the pledge that we are processing
137 * Is this contribution associated with an online
138 * financial transaction
142 public $_online = FALSE;
145 * Stores all product option
152 * Stores the honor id
156 public $_honorID = NULL;
159 * Store the financial Type ID
163 public $_contributionType;
166 * The contribution values if an existing contribution
172 * The pledge values if this contribution is associated with pledge
175 public $_pledgeValues;
177 public $_contributeMode = 'direct';
184 * Store the line items if price set used.
190 * Is this a backoffice form
194 public $isBackOffice = TRUE;
196 protected $_formType;
199 * Payment instrument id for the transaction.
203 public $paymentInstrumentID;
206 * Component - event, membership or contribution.
210 protected $_component;
213 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
214 * be all in this array in order like
215 * 'credit_card' => array('credit_card_number' ...
216 * 'billing_details' => array('first_name' ...
218 * such that both the fields and the order can be more easily altered by payment processors & other extensions
221 public $billingFieldSets = [];
224 * Monetary fields that may be submitted.
226 * These should get a standardised format in the beginPostProcess function.
228 * These fields are common to many forms. Some may override this.
231 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
234 * Pre process function with common actions.
236 * @throws \CRM_Core_Exception
237 * @throws \CiviCRM_API3_Exception
239 public function preProcess() {
240 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
241 if (empty($this->_contactID
) && !empty($this->_id
) && $this->entity
) {
242 $this->_contactID
= civicrm_api3($this->entity
, 'getvalue', ['id' => $this->_id
, 'return' => 'contact_id']);
244 $this->assign('contactID', $this->_contactID
);
245 CRM_Core_Resources
::singleton()->addVars('coreForm', ['contact_id' => (int) $this->_contactID
]);
246 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
247 $this->_mode
= empty($this->_mode
) ? CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this) : $this->_mode
;
248 $this->assign('isBackOffice', $this->isBackOffice
);
249 $this->assignContactEmailDetails();
250 $this->assignPaymentRelatedVariables();
256 public function showRecordLinkMesssage($id) {
257 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
258 if (CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name') == 'Partially paid') {
259 if ($pid = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
260 $recordPaymentLink = CRM_Utils_System
::url('civicrm/payment',
261 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
263 CRM_Core_Session
::setStatus(ts('Please use the <a href="%1">Record Payment</a> form if you have received an additional payment for this Partially paid contribution record.', [1 => $recordPaymentLink]), ts('Notice'), 'alert');
272 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
274 $params = ['id' => $id];
275 CRM_Contribute_BAO_Contribution
::getValues($params, $values, $ids);
277 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
278 $this->_online
= FALSE;
279 $fids = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($id);
280 if (!empty($fids['financialTrxnId'])) {
281 $this->_online
= CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
284 // Also don't allow user to update some fields for recurring contributions.
285 if (!$this->_online
) {
286 $this->_online
= CRM_Utils_Array
::value('contribution_recur_id', $values);
289 $this->assign('isOnline', $this->_online ?
TRUE : FALSE);
292 $daoNote = new CRM_Core_BAO_Note();
293 $daoNote->entity_table
= 'civicrm_contribution';
294 $daoNote->entity_id
= $id;
295 if ($daoNote->find(TRUE)) {
296 $this->_noteID
= $daoNote->id
;
297 $values['note'] = $daoNote->note
;
299 $this->_contributionType
= $values['financial_type_id'];
303 * @param string $type
305 * @param string $subType
306 * @param int $entityId
308 public function applyCustomData($type, $subType, $entityId) {
309 $this->set('type', $type);
310 $this->set('subType', $subType);
311 $this->set('entityId', $entityId);
313 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $subType, 1, $type, $entityId);
314 CRM_Custom_Form_CustomData
::buildQuickForm($this);
315 CRM_Custom_Form_CustomData
::setDefaultValues($this);
320 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
322 public function assignPremiumProduct($id) {
325 FROM civicrm_contribution_product
326 WHERE contribution_id = {$id}
328 $dao = CRM_Core_DAO
::executeQuery($sql);
330 $this->_premiumID
= $dao->id
;
331 $this->_productDAO
= $dao;
337 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
340 public function getValidProcessors() {
341 $capabilities = ['BackOffice'];
343 $capabilities[] = (ucfirst($this->_mode
) . 'Mode');
345 $processors = CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
351 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
353 public function assignProcessors() {
354 //ensure that processor has a valid config
355 //only valid processors get display to user
356 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(['FutureRecurStartDate']));
357 $this->_paymentProcessors
= $this->getValidProcessors();
358 if (!isset($this->_paymentProcessor
['id'])) {
359 // if the payment processor isn't set yet (as indicated by the presence of an id,) we'll grab the first one which should be the default
360 $this->_paymentProcessor
= reset($this->_paymentProcessors
);
363 $this->_paymentProcessor
= $this->_paymentProcessors
[0];
365 elseif (empty($this->_paymentProcessors
) ||
array_keys($this->_paymentProcessors
) === [0]) {
366 throw new CRM_Core_Exception(ts('You will need to configure the %1 settings for your Payment Processor before you can submit a credit card transactions.', [1 => $this->_mode
]));
368 //Assign submitted processor value if it is different from the loaded one.
369 if (!empty($this->_submitValues
['payment_processor_id'])
370 && $this->_paymentProcessor
['id'] != $this->_submitValues
['payment_processor_id']) {
371 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_submitValues
['payment_processor_id']);
373 $this->_processors
= [];
374 foreach ($this->_paymentProcessors
as $id => $processor) {
375 // @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
376 // However the function $this->getValidProcessors() is expected to only return the processors relevant
377 // to the mode (using the actual id - ie. the id of the test processor for the test processor).
378 // for some reason there was a need to filter here per commit history - but this indicates a problem
380 if ($processor['is_test'] == ($this->_mode
== 'test')) {
381 $this->_processors
[$id] = $processor['name'];
382 if (!empty($processor['description'])) {
383 $this->_processors
[$id] .= ' : ' . $processor['description'];
385 if ($processor['is_recur']) {
386 $this->_recurPaymentProcessors
[$id] = $this->_processors
[$id];
390 // CRM-21002: pass the default payment processor ID whose credit card type icons should be populated first
391 CRM_Financial_Form_Payment
::addCreditCardJs($this->_paymentProcessor
['id']);
393 $this->assign('recurringPaymentProcessorIds',
394 empty($this->_recurPaymentProcessors
) ?
'' : implode(',', array_keys($this->_recurPaymentProcessors
))
397 // this required to show billing block
398 // @todo remove this assignment the billing block is now designed to be always included but will not show fieldsets unless those sets of fields are assigned
399 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor
);
403 * Get current currency from DB or use default currency.
405 * @param array $submittedValues
409 public function getCurrency($submittedValues = []) {
410 $config = CRM_Core_Config
::singleton();
412 $currentCurrency = CRM_Utils_Array
::value('currency',
414 $config->defaultCurrency
417 // use submitted currency if present else use current currency
418 $result = CRM_Utils_Array
::value('currency',
425 public function preProcessPledge() {
426 //get the payment values associated with given pledge payment id OR check for payments due.
427 $this->_pledgeValues
= [];
429 $payParams = ['id' => $this->_ppID
];
431 CRM_Pledge_BAO_PledgePayment
::retrieve($payParams, $this->_pledgeValues
['pledgePayment']);
432 $this->_pledgeID
= CRM_Utils_Array
::value('pledge_id', $this->_pledgeValues
['pledgePayment']);
433 $paymentStatusID = CRM_Utils_Array
::value('status_id', $this->_pledgeValues
['pledgePayment']);
434 $this->_id
= CRM_Utils_Array
::value('contribution_id', $this->_pledgeValues
['pledgePayment']);
437 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
438 if (!($paymentStatusID == array_search('Pending', $allStatus) ||
$paymentStatusID == array_search('Overdue', $allStatus))) {
439 CRM_Core_Error
::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
442 //get the pledge values associated with given pledge payment.
445 $pledgeParams = ['id' => $this->_pledgeID
];
446 CRM_Pledge_BAO_Pledge
::getValues($pledgeParams, $this->_pledgeValues
, $ids);
447 $this->assign('ppID', $this->_ppID
);
450 // Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
451 if (isset($this->_contactID
)) {
452 $contactPledges = CRM_Pledge_BAO_Pledge
::getContactPledges($this->_contactID
);
454 if (!empty($contactPledges)) {
455 $payments = $paymentsDue = NULL;
456 $multipleDue = FALSE;
457 foreach ($contactPledges as $key => $pledgeId) {
458 $payments = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
465 $paymentsDue = $payments;
470 // Show link to pledge tab since more than one pledge has a payment due
471 $pledgeTab = CRM_Utils_System
::url('civicrm/contact/view',
472 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
474 CRM_Core_Session
::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', [1 => $pledgeTab]), ts('Notice'), 'alert');
476 elseif ($paymentsDue) {
477 // Show user link to oldest Pending or Overdue pledge payment
478 $ppAmountDue = CRM_Utils_Money
::format($payments['amount'], $payments['currency']);
479 $ppSchedDate = CRM_Utils_Date
::customFormat(CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
481 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
482 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
486 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
487 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
490 CRM_Core_Session
::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', [
494 ]), ts('Notice'), 'alert');
502 * @param array $submittedValues
506 public function unsetCreditCardFields($submittedValues) {
507 //Offline Contribution.
509 'payment_processor_id',
510 "email-{$this->_bltID}",
511 'hidden_buildCreditCard',
512 'hidden_buildDirectDebit',
513 'billing_first_name',
514 'billing_middle_name',
517 "city-{$this->_bltID}",
518 "state_province_id-{$this->_bltID}",
519 "postal_code-{$this->_bltID}",
520 "country_id-{$this->_bltID}",
521 'credit_card_number',
523 'credit_card_exp_date',
526 foreach ($unsetParams as $key) {
527 if (isset($submittedValues[$key])) {
528 unset($submittedValues[$key]);
531 return $submittedValues;
535 * Common block for setting up the parts of a form that relate to credit / debit card
537 protected function assignPaymentRelatedVariables() {
539 $this->assignProcessors();
540 $this->assignBillingType();
541 CRM_Core_Payment_Form
::setPaymentFieldsByProcessor($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer', $this));
543 catch (CRM_Core_Exception
$e) {
544 CRM_Core_Error
::statusBounce($e->getMessage());
549 * Begin post processing.
551 * This function aims to start to bring together common postProcessing functions.
553 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
554 * access this function.
556 protected function beginPostProcess() {
558 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment(
559 $this->_params
['payment_processor_id'],
560 ($this->_mode
== 'test')
562 if (in_array('credit_card_exp_date', array_keys($this->_params
))) {
563 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
564 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
566 $this->assign('credit_card_exp_date', CRM_Utils_Date
::mysqlToIso(CRM_Utils_Date
::format($this->_params
['credit_card_exp_date'])));
567 $this->assign('credit_card_number', CRM_Utils_System
::mungeCreditCard($this->_params
['credit_card_number']));
568 $this->assign('credit_card_type', CRM_Utils_Array
::value('credit_card_type', $this->_params
));
570 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
572 self
::formatCreditCardDetails($this->_params
);
573 foreach ($this->submittableMoneyFields
as $moneyField) {
574 if (isset($this->_params
[$moneyField])) {
575 $this->_params
[$moneyField] = CRM_Utils_Rule
::cleanMoney($this->_params
[$moneyField]);
578 if (!empty($this->_params
['contact_id']) && empty($this->_contactID
)) {
579 // Contact ID has been set in the standalone form.
580 $this->_contactID
= $this->_params
['contact_id'];
581 $this->assignContactEmailDetails();
586 * Format credit card details like:
587 * 1. Retrieve last 4 digit from credit card number as pan_truncation
588 * 2. Retrieve credit card type id from name
590 * @param array $params
594 public static function formatCreditCardDetails(&$params) {
595 if (!empty($params['credit_card_type'])) {
596 $params['card_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $params['credit_card_type']);
598 if (!empty($params['credit_card_number']) && empty($params['pan_truncation'])) {
599 $params['pan_truncation'] = substr($params['credit_card_number'], -4);
604 * Add the billing address to the contact who paid.
606 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
607 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
610 protected function processBillingAddress() {
613 $fields['email-Primary'] = 1;
614 $this->_params
['email-5'] = $this->_params
['email-Primary'] = $this->_contributorEmail
;
615 // now set the values for the billing location.
616 foreach (array_keys($this->_fields
) as $name) {
620 $fields["address_name-{$this->_bltID}"] = 1;
622 //ensure we don't over-write the payer's email with the member's email
623 if ($this->_contributorContactID
== $this->_contactID
) {
624 $fields["email-{$this->_bltID}"] = 1;
627 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
628 $fields = $this->formatParamsForPaymentProcessor($fields);
630 if ($hasBillingField) {
631 $addressParams = array_merge($this->_params
, $addressParams);
632 // CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
633 // Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
634 // Note this source field is covered by a unit test.
635 if (isset($addressParams['source'])) {
636 unset($addressParams['source']);
638 //here we are setting up the billing contact - if different from the member they are already created
639 // but they will get billing details assigned
640 CRM_Contact_BAO_Contact
::createProfileContact($addressParams, $fields,
641 $this->_contributorContactID
, NULL, NULL,
642 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type')
646 $this->assignBillingName($this->_params
);
650 * Get default values for billing fields.
652 * @todo this function still replicates code in several other places in the code.
654 * Also - the call to getProfileDefaults possibly covers the state_province & country already.
660 protected function getBillingDefaults($defaults) {
661 // set default country from config if no country set
662 $config = CRM_Core_Config
::singleton();
663 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
664 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
667 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
668 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
671 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
672 return array_merge($defaults, $billingDefaults);
676 * Get the default payment instrument id.
680 protected function getDefaultPaymentInstrumentId() {
681 $paymentInstrumentID = CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer');
682 if ($paymentInstrumentID) {
683 return $paymentInstrumentID;
685 return key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
689 * Add the payment processor select to the form.
691 * @param bool $isRequired
692 * Is it a mandatory field.
693 * @param bool $isBuildRecurBlock
694 * True if we want to build recur on change
695 * @param bool $isBuildAutoRenewBlock
696 * True if we want to build autorenew on change.
698 protected function addPaymentProcessorSelect($isRequired, $isBuildRecurBlock = FALSE, $isBuildAutoRenewBlock = FALSE) {
702 $js = ($isBuildRecurBlock ?
['onChange' => "buildRecurBlock( this.value ); return false;"] : NULL);
703 if ($isBuildAutoRenewBlock) {
704 $js = ['onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');"];
706 $element = $this->add('select',
707 'payment_processor_id',
708 ts('Payment Processor'),
709 array_diff_key($this->_processors
, [0 => 1]),
713 // The concept of _online is not really explained & the code is old
714 // @todo figure out & document.
715 if ($this->_online
) {
721 * Assign the values to build the payment info block.
726 protected function assignPaymentInfoBlock() {
727 $paymentInfo = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, TRUE);
728 $title = ts('View Payment');
729 if (!empty($this->_component
) && $this->_component
== 'event') {
730 $info = CRM_Event_BAO_Participant
::participantDetails($this->_id
);
731 $title .= " - {$info['title']}";
733 $this->assign('transaction', TRUE);
734 $this->assign('payments', $paymentInfo['transaction']);
735 $this->assign('paymentLinks', $paymentInfo['payment_links']);
739 protected function assignContactEmailDetails() {
740 if ($this->_contactID
) {
741 list($this->userDisplayName
, $this->userEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
742 if (empty($this->userDisplayName
)) {
743 $this->userDisplayName
= civicrm_api3('contact', 'getvalue', ['id' => $this->_contactID
, 'return' => 'display_name']);
745 $this->assign('displayName', $this->userDisplayName
);