3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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
{
55 public $_fields = array();
58 * @var array current payment processor including a copy of the object in 'object' key
60 public $_paymentProcessor;
63 * Available recurring processors.
67 public $_recurPaymentProcessors = array();
70 * Array of processor options in the format id => array($id => $label)
71 * WARNING it appears that the format used to differ to this and there are places in the code that
72 * expect the old format. $this->_paymentProcessors provides the additional data which this
73 * array seems to have provided in the past
79 * Available payment processors with full details including the key 'object' indexed by their id
82 protected $_paymentProcessors = array();
85 * Instance of the payment processor object.
87 * @var CRM_Core_Payment
89 protected $_paymentObject;
92 * The id of the contribution that we are processing.
99 * The id of the premium that we are proceessing.
103 public $_premiumID = NULL;
106 * @var CRM_Contribute_DAO_ContributionProduct
108 public $_productDAO = NULL;
118 * The id of the contact associated with this contribution
125 * The id of the pledge payment that we are processing
132 * The id of the pledge that we are processing
139 * Is this contribution associated with an online
140 * financial transaction
144 public $_online = FALSE;
147 * Stores all product option
154 * Stores the honor id
158 public $_honorID = NULL;
161 * Store the financial Type ID
165 public $_contributionType;
168 * The contribution values if an existing contribution
173 * 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.
189 * Is this a backoffice form
193 public $isBackOffice = TRUE;
195 protected $_formType;
198 * Payment instrument id for the transaction.
202 public $paymentInstrumentID;
205 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
206 * be all in this array in order like
207 * 'credit_card' => array('credit_card_number' ...
208 * 'billing_details' => array('first_name' ...
210 * such that both the fields and the order can be more easily altered by payment processors & other extensions
213 public $billingFieldSets = array();
216 * Pre process function with common actions.
218 public function preProcess() {
219 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
220 $this->assign('contactID', $this->_contactID
);
221 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $this->_contactID
));
222 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
223 $this->_mode
= empty($this->_mode
) ? CRM_Utils_Request
::retrieve('mode', 'String', $this) : $this->_mode
;
224 $this->assignPaymentRelatedVariables();
230 public function showRecordLinkMesssage($id) {
231 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
232 if (CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name') == 'Partially paid') {
233 if ($pid = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
234 $recordPaymentLink = CRM_Utils_System
::url('civicrm/payment',
235 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
237 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');
246 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
248 $params = array('id' => $id);
249 CRM_Contribute_BAO_Contribution
::getValues($params, $values, $ids);
251 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
252 $this->_online
= FALSE;
253 $fids = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($id);
254 if (!empty($fids['financialTrxnId'])) {
255 $this->_online
= CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
258 // Also don't allow user to update some fields for recurring contributions.
259 if (!$this->_online
) {
260 $this->_online
= CRM_Utils_Array
::value('contribution_recur_id', $values);
263 $this->assign('isOnline', $this->_online ?
TRUE : FALSE);
266 $daoNote = new CRM_Core_BAO_Note();
267 $daoNote->entity_table
= 'civicrm_contribution';
268 $daoNote->entity_id
= $id;
269 if ($daoNote->find(TRUE)) {
270 $this->_noteID
= $daoNote->id
;
271 $values['note'] = $daoNote->note
;
273 $this->_contributionType
= $values['financial_type_id'];
277 * @param string $type
279 * @param string $subType
280 * @param int $entityId
282 public function applyCustomData($type, $subType, $entityId) {
283 $this->set('type', $type);
284 $this->set('subType', $subType);
285 $this->set('entityId', $entityId);
287 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $subType, 1, $type, $entityId);
288 CRM_Custom_Form_CustomData
::buildQuickForm($this);
289 CRM_Custom_Form_CustomData
::setDefaultValues($this);
294 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
296 public function assignPremiumProduct($id) {
299 FROM civicrm_contribution_product
300 WHERE contribution_id = {$id}
302 $dao = CRM_Core_DAO
::executeQuery($sql,
303 CRM_Core_DAO
::$_nullArray
306 $this->_premiumID
= $dao->id
;
307 $this->_productDAO
= $dao;
314 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
317 public function getValidProcessors() {
318 $capabilities = array('BackOffice');
320 $capabilities[] = (ucfirst($this->_mode
) . 'Mode');
322 $processors = CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
328 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
330 public function assignProcessors() {
331 //ensure that processor has a valid config
332 //only valid processors get display to user
333 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('FutureRecurStartDate')));
334 $this->_paymentProcessors
= $this->getValidProcessors();
335 if (!isset($this->_paymentProcessor
['id'])) {
336 // 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
337 $this->_paymentProcessor
= reset($this->_paymentProcessors
);
340 $this->_paymentProcessor
= $this->_paymentProcessors
[0];
342 elseif (empty($this->_paymentProcessors
) ||
array_keys($this->_paymentProcessors
) === array(0)) {
343 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
)));
345 $this->_processors
= array();
346 foreach ($this->_paymentProcessors
as $id => $processor) {
347 // @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
348 // However the function $this->getValidProcessors() is expected to only return the processors relevant
349 // to the mode (using the actual id - ie. the id of the test processor for the test processor).
350 // for some reason there was a need to filter here per commit history - but this indicates a problem
352 if ($processor['is_test'] == ($this->_mode
== 'test')) {
353 $this->_processors
[$id] = ts($processor['name']);
354 if (!empty($processor['description'])) {
355 $this->_processors
[$id] .= ' : ' . ts($processor['description']);
357 if ($processor['is_recur']) {
358 $this->_recurPaymentProcessors
[$id] = $this->_processors
[$id];
362 CRM_Financial_Form_Payment
::addCreditCardJs($id);
364 $this->assign('recurringPaymentProcessorIds',
365 empty($this->_recurPaymentProcessors
) ?
'' : implode(',', array_keys($this->_recurPaymentProcessors
))
368 // this required to show billing block
369 // @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
370 $this->assign_by_ref('paymentProcessor', $processor);
374 * Get current currency from DB or use default currency.
376 * @param $submittedValues
380 public function getCurrency($submittedValues) {
381 $config = CRM_Core_Config
::singleton();
383 $currentCurrency = CRM_Utils_Array
::value('currency',
385 $config->defaultCurrency
388 // use submitted currency if present else use current currency
389 $result = CRM_Utils_Array
::value('currency',
396 public function preProcessPledge() {
397 //get the payment values associated with given pledge payment id OR check for payments due.
398 $this->_pledgeValues
= array();
400 $payParams = array('id' => $this->_ppID
);
402 CRM_Pledge_BAO_PledgePayment
::retrieve($payParams, $this->_pledgeValues
['pledgePayment']);
403 $this->_pledgeID
= CRM_Utils_Array
::value('pledge_id', $this->_pledgeValues
['pledgePayment']);
404 $paymentStatusID = CRM_Utils_Array
::value('status_id', $this->_pledgeValues
['pledgePayment']);
405 $this->_id
= CRM_Utils_Array
::value('contribution_id', $this->_pledgeValues
['pledgePayment']);
408 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
409 if (!($paymentStatusID == array_search('Pending', $allStatus) ||
$paymentStatusID == array_search('Overdue', $allStatus))) {
410 CRM_Core_Error
::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
413 //get the pledge values associated with given pledge payment.
416 $pledgeParams = array('id' => $this->_pledgeID
);
417 CRM_Pledge_BAO_Pledge
::getValues($pledgeParams, $this->_pledgeValues
, $ids);
418 $this->assign('ppID', $this->_ppID
);
421 // 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
422 if (isset($this->_contactID
)) {
423 $contactPledges = CRM_Pledge_BAO_Pledge
::getContactPledges($this->_contactID
);
425 if (!empty($contactPledges)) {
426 $payments = $paymentsDue = NULL;
427 $multipleDue = FALSE;
428 foreach ($contactPledges as $key => $pledgeId) {
429 $payments = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
436 $paymentsDue = $payments;
441 // Show link to pledge tab since more than one pledge has a payment due
442 $pledgeTab = CRM_Utils_System
::url('civicrm/contact/view',
443 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
445 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');
447 elseif ($paymentsDue) {
448 // Show user link to oldest Pending or Overdue pledge payment
449 $ppAmountDue = CRM_Utils_Money
::format($payments['amount'], $payments['currency']);
450 $ppSchedDate = CRM_Utils_Date
::customFormat(CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
452 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
453 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
457 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
458 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
461 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(
465 )), ts('Notice'), 'alert');
473 * @param array $submittedValues
477 public function unsetCreditCardFields($submittedValues) {
478 //Offline Contribution.
479 $unsetParams = array(
480 'payment_processor_id',
481 "email-{$this->_bltID}",
482 'hidden_buildCreditCard',
483 'hidden_buildDirectDebit',
484 'billing_first_name',
485 'billing_middle_name',
488 "city-{$this->_bltID}",
489 "state_province_id-{$this->_bltID}",
490 "postal_code-{$this->_bltID}",
491 "country_id-{$this->_bltID}",
492 'credit_card_number',
494 'credit_card_exp_date',
497 foreach ($unsetParams as $key) {
498 if (isset($submittedValues[$key])) {
499 unset($submittedValues[$key]);
502 return $submittedValues;
506 * Common block for setting up the parts of a form that relate to credit / debit card
509 protected function assignPaymentRelatedVariables() {
511 if ($this->_contactID
) {
512 list($this->userDisplayName
, $this->userEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
513 $this->assign('displayName', $this->userDisplayName
);
515 $this->assignProcessors();
516 $this->assignBillingType();
517 CRM_Core_Payment_Form
::setPaymentFieldsByProcessor($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer'));
519 catch (CRM_Core_Exception
$e) {
520 CRM_Core_Error
::fatal($e->getMessage());
525 * Begin post processing.
527 * This function aims to start to bring together common postProcessing functions.
529 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
530 * access this function.
532 protected function beginPostProcess() {
534 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment(
535 $this->_params
['payment_processor_id'],
536 ($this->_mode
== 'test')
538 if (in_array('credit_card_exp_date', array_keys($this->_params
))) {
539 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
540 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
542 $this->assign('credit_card_exp_date', CRM_Utils_Date
::mysqlToIso(CRM_Utils_Date
::format($this->_params
['credit_card_exp_date'])));
543 $this->assign('credit_card_number',
544 CRM_Utils_System
::mungeCreditCard($this->_params
['credit_card_number'])
546 $this->assign('credit_card_type', CRM_Utils_Array
::value('credit_card_type', $this->_params
));
548 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
549 if (in_array('credit_card_type', array_keys($this->_params
))) {
550 $this->_params
['card_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params
['credit_card_type']);
552 if (!empty($this->_params
['credit_card_number']) && empty($this->_params
['pan_truncation'])) {
553 $this->_params
['pan_truncation'] = substr($this->_params
['credit_card_number'], -4);
560 * Add the billing address to the contact who paid.
562 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
563 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
566 protected function processBillingAddress() {
569 $fields['email-Primary'] = 1;
570 $this->_params
['email-5'] = $this->_params
['email-Primary'] = $this->_contributorEmail
;
571 // now set the values for the billing location.
572 foreach (array_keys($this->_fields
) as $name) {
576 $fields["address_name-{$this->_bltID}"] = 1;
578 //ensure we don't over-write the payer's email with the member's email
579 if ($this->_contributorContactID
== $this->_contactID
) {
580 $fields["email-{$this->_bltID}"] = 1;
583 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
584 $fields = $this->formatParamsForPaymentProcessor($fields);
586 if ($hasBillingField) {
587 $addressParams = array_merge($this->_params
, $addressParams);
588 // CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
589 // Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
590 // Note this source field is covered by a unit test.
591 if (isset($addressParams['source'])) {
592 unset($addressParams['source']);
594 //here we are setting up the billing contact - if different from the member they are already created
595 // but they will get billing details assigned
596 CRM_Contact_BAO_Contact
::createProfileContact($addressParams, $fields,
597 $this->_contributorContactID
, NULL, NULL,
598 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type')
604 * Get default values for billing fields.
606 * @todo this function still replicates code in several other places in the code.
608 * Also - the call to getProfileDefaults possibly covers the state_province & country already.
614 protected function getBillingDefaults($defaults) {
615 // set default country from config if no country set
616 $config = CRM_Core_Config
::singleton();
617 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
618 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
621 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
622 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
625 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
626 return array_merge($defaults, $billingDefaults);
630 * Get the default payment instrument id.
634 protected function getDefaultPaymentInstrumentId() {
635 $paymentInstrumentID = CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer');
636 if ($paymentInstrumentID) {
637 return $paymentInstrumentID;
639 return key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));