3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * This class generates form components for processing a contribution
36 * CRM-16229 - During the event registration bulk action via search we
37 * need to inherit CRM_Contact_Form_Task so that we can inherit functions
38 * like getContactIds and make use of controller state. But this is not possible
39 * because CRM_Event_Form_Participant inherits this class.
40 * Ideal situation would be something like
41 * CRM_Event_Form_Participant extends CRM_Contact_Form_Task,
42 * CRM_Contribute_Form_AbstractEditPayment
43 * However this is not possible. Currently PHP does not support multiple
44 * inheritance. So work around solution is to extend this class with
45 * CRM_Contact_Form_Task which further extends CRM_Core_Form.
48 class CRM_Contribute_Form_AbstractEditPayment
extends CRM_Contact_Form_Task
{
50 use CRM_Financial_Form_SalesTaxTrait
;
58 public $_fields = array();
61 * @var array current payment processor including a copy of the object in 'object' key
63 public $_paymentProcessor;
66 * Available recurring processors.
70 public $_recurPaymentProcessors = array();
73 * Array of processor options in the format id => array($id => $label)
74 * WARNING it appears that the format used to differ to this and there are places in the code that
75 * expect the old format. $this->_paymentProcessors provides the additional data which this
76 * array seems to have provided in the past
82 * Available payment processors with full details including the key 'object' indexed by their id
85 protected $_paymentProcessors = array();
88 * Instance of the payment processor object.
90 * @var CRM_Core_Payment
92 protected $_paymentObject;
95 * The id of the contribution that we are processing.
102 * Entity that $this->_id relates to.
104 * If set the contact id is not required in the url.
111 * The id of the premium that we are proceessing.
115 public $_premiumID = NULL;
118 * @var CRM_Contribute_DAO_ContributionProduct
120 public $_productDAO = NULL;
130 * The id of the contact associated with this contribution
137 * The id of the pledge payment that we are processing
144 * The id of the pledge that we are processing
151 * Is this contribution associated with an online
152 * financial transaction
156 public $_online = FALSE;
159 * Stores all product option
166 * Stores the honor id
170 public $_honorID = NULL;
173 * Store the financial Type ID
177 public $_contributionType;
180 * The contribution values if an existing contribution
185 * The pledge values if this contribution is associated with pledge
187 public $_pledgeValues;
189 public $_contributeMode = 'direct';
196 * Store the line items if price set used.
201 * Is this a backoffice form
205 public $isBackOffice = TRUE;
207 protected $_formType;
210 * Payment instrument id for the transaction.
214 public $paymentInstrumentID;
217 * Component - event, membership or contribution.
221 protected $_component;
224 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
225 * be all in this array in order like
226 * 'credit_card' => array('credit_card_number' ...
227 * 'billing_details' => array('first_name' ...
229 * such that both the fields and the order can be more easily altered by payment processors & other extensions
232 public $billingFieldSets = array();
235 * Monetary fields that may be submitted.
237 * These should get a standardised format in the beginPostProcess function.
239 * These fields are common to many forms. Some may override this.
241 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
244 * Pre process function with common actions.
246 public function preProcess() {
247 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
248 if (empty($this->_contactID
) && !empty($this->_id
) && $this->entity
) {
249 $this->_contactID
= civicrm_api3($this->entity
, 'getvalue', array('id' => $this->_id
, 'return' => 'contact_id'));
251 $this->assign('contactID', $this->_contactID
);
252 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $this->_contactID
));
253 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
254 $this->_mode
= empty($this->_mode
) ? CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this) : $this->_mode
;
255 $this->assign('isBackOffice', $this->isBackOffice
);
256 $this->assignContactEmailDetails();
257 $this->assignPaymentRelatedVariables();
263 public function showRecordLinkMesssage($id) {
264 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
265 if (CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name') == 'Partially paid') {
266 if ($pid = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
267 $recordPaymentLink = CRM_Utils_System
::url('civicrm/payment',
268 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
270 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.', array(1 => $recordPaymentLink)), ts('Notice'), 'alert');
279 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
281 $params = array('id' => $id);
282 CRM_Contribute_BAO_Contribution
::getValues($params, $values, $ids);
284 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
285 $this->_online
= FALSE;
286 $fids = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($id);
287 if (!empty($fids['financialTrxnId'])) {
288 $this->_online
= CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
291 // Also don't allow user to update some fields for recurring contributions.
292 if (!$this->_online
) {
293 $this->_online
= CRM_Utils_Array
::value('contribution_recur_id', $values);
296 $this->assign('isOnline', $this->_online ?
TRUE : FALSE);
299 $daoNote = new CRM_Core_BAO_Note();
300 $daoNote->entity_table
= 'civicrm_contribution';
301 $daoNote->entity_id
= $id;
302 if ($daoNote->find(TRUE)) {
303 $this->_noteID
= $daoNote->id
;
304 $values['note'] = $daoNote->note
;
306 $this->_contributionType
= $values['financial_type_id'];
310 * @param string $type
312 * @param string $subType
313 * @param int $entityId
315 public function applyCustomData($type, $subType, $entityId) {
316 $this->set('type', $type);
317 $this->set('subType', $subType);
318 $this->set('entityId', $entityId);
320 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $subType, 1, $type, $entityId);
321 CRM_Custom_Form_CustomData
::buildQuickForm($this);
322 CRM_Custom_Form_CustomData
::setDefaultValues($this);
327 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
329 public function assignPremiumProduct($id) {
332 FROM civicrm_contribution_product
333 WHERE contribution_id = {$id}
335 $dao = CRM_Core_DAO
::executeQuery($sql,
336 CRM_Core_DAO
::$_nullArray
339 $this->_premiumID
= $dao->id
;
340 $this->_productDAO
= $dao;
347 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
350 public function getValidProcessors() {
351 $capabilities = array('BackOffice');
353 $capabilities[] = (ucfirst($this->_mode
) . 'Mode');
355 $processors = CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
361 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
363 public function assignProcessors() {
364 //ensure that processor has a valid config
365 //only valid processors get display to user
366 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('FutureRecurStartDate')));
367 $this->_paymentProcessors
= $this->getValidProcessors();
368 if (!isset($this->_paymentProcessor
['id'])) {
369 // 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
370 $this->_paymentProcessor
= reset($this->_paymentProcessors
);
373 $this->_paymentProcessor
= $this->_paymentProcessors
[0];
375 elseif (empty($this->_paymentProcessors
) ||
array_keys($this->_paymentProcessors
) === array(0)) {
376 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.', array(1 => $this->_mode
)));
378 //Assign submitted processor value if it is different from the loaded one.
379 if (!empty($this->_submitValues
['payment_processor_id'])
380 && $this->_paymentProcessor
['id'] != $this->_submitValues
['payment_processor_id']) {
381 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_submitValues
['payment_processor_id']);
383 $this->_processors
= array();
384 foreach ($this->_paymentProcessors
as $id => $processor) {
385 // @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
386 // However the function $this->getValidProcessors() is expected to only return the processors relevant
387 // to the mode (using the actual id - ie. the id of the test processor for the test processor).
388 // for some reason there was a need to filter here per commit history - but this indicates a problem
390 if ($processor['is_test'] == ($this->_mode
== 'test')) {
391 $this->_processors
[$id] = ts($processor['name']);
392 if (!empty($processor['description'])) {
393 $this->_processors
[$id] .= ' : ' . ts($processor['description']);
395 if ($processor['is_recur']) {
396 $this->_recurPaymentProcessors
[$id] = $this->_processors
[$id];
400 // CRM-21002: pass the default payment processor ID whose credit card type icons should be populated first
401 CRM_Financial_Form_Payment
::addCreditCardJs($this->_paymentProcessor
['id']);
403 $this->assign('recurringPaymentProcessorIds',
404 empty($this->_recurPaymentProcessors
) ?
'' : implode(',', array_keys($this->_recurPaymentProcessors
))
407 // this required to show billing block
408 // @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
409 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor
);
413 * Get current currency from DB or use default currency.
415 * @param array $submittedValues
419 public function getCurrency($submittedValues = array()) {
420 $config = CRM_Core_Config
::singleton();
422 $currentCurrency = CRM_Utils_Array
::value('currency',
424 $config->defaultCurrency
427 // use submitted currency if present else use current currency
428 $result = CRM_Utils_Array
::value('currency',
435 public function preProcessPledge() {
436 //get the payment values associated with given pledge payment id OR check for payments due.
437 $this->_pledgeValues
= array();
439 $payParams = array('id' => $this->_ppID
);
441 CRM_Pledge_BAO_PledgePayment
::retrieve($payParams, $this->_pledgeValues
['pledgePayment']);
442 $this->_pledgeID
= CRM_Utils_Array
::value('pledge_id', $this->_pledgeValues
['pledgePayment']);
443 $paymentStatusID = CRM_Utils_Array
::value('status_id', $this->_pledgeValues
['pledgePayment']);
444 $this->_id
= CRM_Utils_Array
::value('contribution_id', $this->_pledgeValues
['pledgePayment']);
447 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
448 if (!($paymentStatusID == array_search('Pending', $allStatus) ||
$paymentStatusID == array_search('Overdue', $allStatus))) {
449 CRM_Core_Error
::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
452 //get the pledge values associated with given pledge payment.
455 $pledgeParams = array('id' => $this->_pledgeID
);
456 CRM_Pledge_BAO_Pledge
::getValues($pledgeParams, $this->_pledgeValues
, $ids);
457 $this->assign('ppID', $this->_ppID
);
460 // 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
461 if (isset($this->_contactID
)) {
462 $contactPledges = CRM_Pledge_BAO_Pledge
::getContactPledges($this->_contactID
);
464 if (!empty($contactPledges)) {
465 $payments = $paymentsDue = NULL;
466 $multipleDue = FALSE;
467 foreach ($contactPledges as $key => $pledgeId) {
468 $payments = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
475 $paymentsDue = $payments;
480 // Show link to pledge tab since more than one pledge has a payment due
481 $pledgeTab = CRM_Utils_System
::url('civicrm/contact/view',
482 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
484 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.', array(1 => $pledgeTab)), ts('Notice'), 'alert');
486 elseif ($paymentsDue) {
487 // Show user link to oldest Pending or Overdue pledge payment
488 $ppAmountDue = CRM_Utils_Money
::format($payments['amount'], $payments['currency']);
489 $ppSchedDate = CRM_Utils_Date
::customFormat(CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
491 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
492 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
496 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
497 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
500 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>.', array(
504 )), ts('Notice'), 'alert');
512 * @param array $submittedValues
516 public function unsetCreditCardFields($submittedValues) {
517 //Offline Contribution.
518 $unsetParams = array(
519 'payment_processor_id',
520 "email-{$this->_bltID}",
521 'hidden_buildCreditCard',
522 'hidden_buildDirectDebit',
523 'billing_first_name',
524 'billing_middle_name',
527 "city-{$this->_bltID}",
528 "state_province_id-{$this->_bltID}",
529 "postal_code-{$this->_bltID}",
530 "country_id-{$this->_bltID}",
531 'credit_card_number',
533 'credit_card_exp_date',
536 foreach ($unsetParams as $key) {
537 if (isset($submittedValues[$key])) {
538 unset($submittedValues[$key]);
541 return $submittedValues;
545 * Common block for setting up the parts of a form that relate to credit / debit card
548 protected function assignPaymentRelatedVariables() {
550 $this->assignProcessors();
551 $this->assignBillingType();
552 CRM_Core_Payment_Form
::setPaymentFieldsByProcessor($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer', $this));
554 catch (CRM_Core_Exception
$e) {
555 CRM_Core_Error
::statusBounce($e->getMessage());
560 * Begin post processing.
562 * This function aims to start to bring together common postProcessing functions.
564 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
565 * access this function.
567 protected function beginPostProcess() {
569 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment(
570 $this->_params
['payment_processor_id'],
571 ($this->_mode
== 'test')
573 if (in_array('credit_card_exp_date', array_keys($this->_params
))) {
574 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
575 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
577 $this->assign('credit_card_exp_date', CRM_Utils_Date
::mysqlToIso(CRM_Utils_Date
::format($this->_params
['credit_card_exp_date'])));
578 $this->assign('credit_card_number',
579 CRM_Utils_System
::mungeCreditCard($this->_params
['credit_card_number'])
581 $this->assign('credit_card_type', CRM_Utils_Array
::value('credit_card_type', $this->_params
));
583 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
585 self
::formatCreditCardDetails($this->_params
);
586 foreach ($this->submittableMoneyFields
as $moneyField) {
587 if (isset($this->_params
[$moneyField])) {
588 $this->_params
[$moneyField] = CRM_Utils_Rule
::cleanMoney($this->_params
[$moneyField]);
591 if (!empty($this->_params
['contact_id']) && empty($this->_contactID
)) {
592 // Contact ID has been set in the standalone form.
593 $this->_contactID
= $this->_params
['contact_id'];
594 $this->assignContactEmailDetails();
599 * Format credit card details like:
600 * 1. Retrieve last 4 digit from credit card number as pan_truncation
601 * 2. Retrieve credit card type id from name
603 * @param array $params
607 public static function formatCreditCardDetails(&$params) {
608 if (in_array('credit_card_type', array_keys($params))) {
609 $params['card_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $params['credit_card_type']);
611 if (!empty($params['credit_card_number']) && empty($params['pan_truncation'])) {
612 $params['pan_truncation'] = substr($params['credit_card_number'], -4);
617 * Add the billing address to the contact who paid.
619 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
620 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
623 protected function processBillingAddress() {
626 $fields['email-Primary'] = 1;
627 $this->_params
['email-5'] = $this->_params
['email-Primary'] = $this->_contributorEmail
;
628 // now set the values for the billing location.
629 foreach (array_keys($this->_fields
) as $name) {
633 $fields["address_name-{$this->_bltID}"] = 1;
635 //ensure we don't over-write the payer's email with the member's email
636 if ($this->_contributorContactID
== $this->_contactID
) {
637 $fields["email-{$this->_bltID}"] = 1;
640 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
641 $fields = $this->formatParamsForPaymentProcessor($fields);
643 if ($hasBillingField) {
644 $addressParams = array_merge($this->_params
, $addressParams);
645 // CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
646 // Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
647 // Note this source field is covered by a unit test.
648 if (isset($addressParams['source'])) {
649 unset($addressParams['source']);
651 //here we are setting up the billing contact - if different from the member they are already created
652 // but they will get billing details assigned
653 CRM_Contact_BAO_Contact
::createProfileContact($addressParams, $fields,
654 $this->_contributorContactID
, NULL, NULL,
655 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type')
659 $this->assignBillingName($this->_params
);
663 * Get default values for billing fields.
665 * @todo this function still replicates code in several other places in the code.
667 * Also - the call to getProfileDefaults possibly covers the state_province & country already.
673 protected function getBillingDefaults($defaults) {
674 // set default country from config if no country set
675 $config = CRM_Core_Config
::singleton();
676 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
677 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
680 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
681 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
684 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
685 return array_merge($defaults, $billingDefaults);
689 * Get the default payment instrument id.
693 protected function getDefaultPaymentInstrumentId() {
694 $paymentInstrumentID = CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer');
695 if ($paymentInstrumentID) {
696 return $paymentInstrumentID;
698 return key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
702 * Add the payment processor select to the form.
704 * @param bool $isRequired
705 * Is it a mandatory field.
706 * @param bool $isBuildRecurBlock
707 * True if we want to build recur on change
708 * @param bool $isBuildAutoRenewBlock
709 * True if we want to build autorenew on change.
711 protected function addPaymentProcessorSelect($isRequired, $isBuildRecurBlock = FALSE, $isBuildAutoRenewBlock = FALSE) {
715 $js = ($isBuildRecurBlock ?
array('onChange' => "buildRecurBlock( this.value ); return false;") : NULL);
716 if ($isBuildAutoRenewBlock) {
717 $js = array('onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');");
719 $element = $this->add('select',
720 'payment_processor_id',
721 ts('Payment Processor'),
722 array_diff_key($this->_processors
, array(0 => 1)),
726 // The concept of _online is not really explained & the code is old
727 // @todo figure out & document.
728 if ($this->_online
) {
735 * Assign the values to build the payment info block.
737 * @return string $title
740 protected function assignPaymentInfoBlock() {
741 $paymentInfo = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, TRUE);
742 $title = ts('View Payment');
743 if (!empty($this->_component
) && $this->_component
== 'event') {
744 $info = CRM_Event_BAO_Participant
::participantDetails($this->_id
);
745 $title .= " - {$info['title']}";
747 $this->assign('transaction', TRUE);
748 $this->assign('payments', $paymentInfo['transaction']);
749 $this->assign('paymentLinks', $paymentInfo['payment_links']);
753 protected function assignContactEmailDetails() {
754 if ($this->_contactID
) {
755 list($this->userDisplayName
, $this->userEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
756 if (empty($this->userDisplayName
)) {
757 $this->userDisplayName
= civicrm_api3('contact', 'getvalue', ['id' => $this->_contactID
, 'return' => 'display_name']);
759 $this->assign('displayName', $this->userDisplayName
);