3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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
190 * (this will affect whether paypal express code is displayed)
193 public $isBackOffice = TRUE;
195 protected $_formType;
198 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
199 * be all in this array in order like
200 * 'credit_card' => array('credit_card_number' ...
201 * 'billing_details' => array('first_name' ...
203 * such that both the fields and the order can be more easily altered by payment processors & other extensions
206 public $billingFieldSets = array();
209 * Pre process function with common actions.
211 public function preProcess() {
212 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
213 $this->assign('contactID', $this->_contactID
);
214 CRM_Core_Resources
::singleton()->addVars('coreForm', array('contact_id' => (int) $this->_contactID
));
215 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
221 public function showRecordLinkMesssage($id) {
222 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
223 if (CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name') == 'Partially paid') {
224 if ($pid = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
225 $recordPaymentLink = CRM_Utils_System
::url('civicrm/payment',
226 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
228 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');
237 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
239 $params = array('id' => $id);
240 CRM_Contribute_BAO_Contribution
::getValues($params, $values, $ids);
242 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
243 $this->_online
= FALSE;
244 $fids = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($id);
245 if (!empty($fids['financialTrxnId'])) {
246 $this->_online
= CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
249 // Also don't allow user to update some fields for recurring contributions.
250 if (!$this->_online
) {
251 $this->_online
= CRM_Utils_Array
::value('contribution_recur_id', $values);
254 $this->assign('isOnline', $this->_online ?
TRUE : FALSE);
257 $daoNote = new CRM_Core_BAO_Note();
258 $daoNote->entity_table
= 'civicrm_contribution';
259 $daoNote->entity_id
= $id;
260 if ($daoNote->find(TRUE)) {
261 $this->_noteID
= $daoNote->id
;
262 $values['note'] = $daoNote->note
;
264 $this->_contributionType
= $values['financial_type_id'];
268 * @param string $type
270 * @param string $subType
271 * @param int $entityId
273 public function applyCustomData($type, $subType, $entityId) {
274 $this->set('type', $type);
275 $this->set('subType', $subType);
276 $this->set('entityId', $entityId);
278 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $subType, 1, $type, $entityId);
279 CRM_Custom_Form_CustomData
::buildQuickForm($this);
280 CRM_Custom_Form_CustomData
::setDefaultValues($this);
285 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
287 public function assignPremiumProduct($id) {
290 FROM civicrm_contribution_product
291 WHERE contribution_id = {$id}
293 $dao = CRM_Core_DAO
::executeQuery($sql,
294 CRM_Core_DAO
::$_nullArray
297 $this->_premiumID
= $dao->id
;
298 $this->_productDAO
= $dao;
304 * This function process contribution related objects.
306 * @param int $contributionId
307 * @param int $statusId
308 * @param int|null $previousStatusId
310 * @return null|string
312 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
314 if (!$contributionId ||
!$statusId) {
319 'contribution_id' => $contributionId,
320 'contribution_status_id' => $statusId,
321 'previous_contribution_status_id' => $previousStatusId,
322 'receive_date' => $receiveDate,
325 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
327 if (!is_array($updateResult) ||
328 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
329 !is_array($updatedComponents) ||
330 empty($updatedComponents)
335 // get the user display name.
337 SELECT display_name as displayName
339 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
340 WHERE civicrm_contribution.id = {$contributionId}";
341 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
343 // get the status message for user.
344 foreach ($updatedComponents as $componentName => $updatedStatusId) {
346 if ($componentName == 'CiviMember') {
347 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
348 CRM_Member_PseudoConstant
::membershipStatus()
350 if ($updatedStatusName == 'Cancelled') {
351 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
353 elseif ($updatedStatusName == 'Expired') {
354 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
357 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
359 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
361 1 => $userDisplayName,
369 if ($componentName == 'CiviEvent') {
370 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
371 CRM_Event_PseudoConstant
::participantStatus()
373 if ($updatedStatusName == 'Cancelled') {
374 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
376 elseif ($updatedStatusName == 'Registered') {
377 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
381 if ($componentName == 'CiviPledge') {
382 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
383 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
385 if ($updatedStatusName == 'Cancelled') {
386 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
388 elseif ($updatedStatusName == 'Failed') {
389 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
391 elseif ($updatedStatusName == 'Completed') {
392 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
402 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
405 public function getValidProcessors() {
407 $capabilities = array('BackOffice');
409 $capabilities[] = (ucfirst($this->_mode
) . 'Mode');
411 $processors = CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
417 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
419 public function assignProcessors() {
420 //ensure that processor has a valid config
421 //only valid processors get display to user
424 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('FutureRecurStartDate')));
425 $this->_paymentProcessors
= $this->getValidProcessors();
426 if (!isset($this->_paymentProcessor
['id'])) {
427 // 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
428 $this->_paymentProcessor
= reset($this->_paymentProcessors
);
430 if (empty($this->_paymentProcessors
)) {
431 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
)));
433 $this->_processors
= array();
434 foreach ($this->_paymentProcessors
as $id => $processor) {
435 // @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
436 // However the function $this->getValidProcessors() is expected to only return the processors relevant
437 // to the mode (using the actual id - ie. the id of the test processor for the test processor).
438 // for some reason there was a need to filter here per commit history - but this indicates a problem
440 if ($processor['is_test'] == ($this->_mode
== 'test')) {
441 $this->_processors
[$id] = ts($processor['name']);
442 if (!empty($processor['description'])) {
443 $this->_processors
[$id] .= ' : ' . ts($processor['description']);
445 if ($processor['is_recur']) {
446 $this->_recurPaymentProcessors
[$id] = $this->_processors
[$id];
450 CRM_Financial_Form_Payment
::addCreditCardJs();
452 $this->assign('recurringPaymentProcessorIds',
453 empty($this->_recurPaymentProcessors
) ?
'' : implode(',', array_keys($this->_recurPaymentProcessors
))
456 // this required to show billing block
457 // @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
458 $this->assign_by_ref('paymentProcessor', $processor);
462 * Get current currency from DB or use default currency.
464 * @param $submittedValues
468 public function getCurrency($submittedValues) {
469 $config = CRM_Core_Config
::singleton();
471 $currentCurrency = CRM_Utils_Array
::value('currency',
473 $config->defaultCurrency
476 // use submitted currency if present else use current currency
477 $result = CRM_Utils_Array
::value('currency',
485 * @param int $financialTypeId
489 public function getFinancialAccounts($financialTypeId) {
490 $financialAccounts = array();
491 CRM_Core_PseudoConstant
::populate($financialAccounts,
492 'CRM_Financial_DAO_EntityFinancialAccount',
494 $retrieve = 'financial_account_id',
496 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
497 return $financialAccounts;
501 * @param int $financialTypeId
502 * @param int $relationTypeId
506 public function getFinancialAccount($financialTypeId, $relationTypeId) {
507 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
508 return CRM_Utils_Array
::value($relationTypeId, $financialAccounts);
511 public function preProcessPledge() {
512 //get the payment values associated with given pledge payment id OR check for payments due.
513 $this->_pledgeValues
= array();
515 $payParams = array('id' => $this->_ppID
);
517 CRM_Pledge_BAO_PledgePayment
::retrieve($payParams, $this->_pledgeValues
['pledgePayment']);
518 $this->_pledgeID
= CRM_Utils_Array
::value('pledge_id', $this->_pledgeValues
['pledgePayment']);
519 $paymentStatusID = CRM_Utils_Array
::value('status_id', $this->_pledgeValues
['pledgePayment']);
520 $this->_id
= CRM_Utils_Array
::value('contribution_id', $this->_pledgeValues
['pledgePayment']);
523 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
524 if (!($paymentStatusID == array_search('Pending', $allStatus) ||
$paymentStatusID == array_search('Overdue', $allStatus))) {
525 CRM_Core_Error
::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
528 //get the pledge values associated with given pledge payment.
531 $pledgeParams = array('id' => $this->_pledgeID
);
532 CRM_Pledge_BAO_Pledge
::getValues($pledgeParams, $this->_pledgeValues
, $ids);
533 $this->assign('ppID', $this->_ppID
);
536 // 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
537 if (isset($this->_contactID
)) {
538 $contactPledges = CRM_Pledge_BAO_Pledge
::getContactPledges($this->_contactID
);
540 if (!empty($contactPledges)) {
541 $payments = $paymentsDue = NULL;
542 $multipleDue = FALSE;
543 foreach ($contactPledges as $key => $pledgeId) {
544 $payments = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
551 $paymentsDue = $payments;
556 // Show link to pledge tab since more than one pledge has a payment due
557 $pledgeTab = CRM_Utils_System
::url('civicrm/contact/view',
558 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
560 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');
562 elseif ($paymentsDue) {
563 // Show user link to oldest Pending or Overdue pledge payment
564 $ppAmountDue = CRM_Utils_Money
::format($payments['amount'], $payments['currency']);
565 $ppSchedDate = CRM_Utils_Date
::customFormat(CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
567 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
568 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
572 $ppUrl = CRM_Utils_System
::url('civicrm/contact/view/contribution',
573 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
576 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(
580 )), ts('Notice'), 'alert');
588 * @param array $submittedValues
592 public function unsetCreditCardFields($submittedValues) {
593 //Offline Contribution.
594 $unsetParams = array(
595 'payment_processor_id',
596 "email-{$this->_bltID}",
597 'hidden_buildCreditCard',
598 'hidden_buildDirectDebit',
599 'billing_first_name',
600 'billing_middle_name',
603 "city-{$this->_bltID}",
604 "state_province_id-{$this->_bltID}",
605 "postal_code-{$this->_bltID}",
606 "country_id-{$this->_bltID}",
607 'credit_card_number',
609 'credit_card_exp_date',
612 foreach ($unsetParams as $key) {
613 if (isset($submittedValues[$key])) {
614 unset($submittedValues[$key]);
617 return $submittedValues;
621 * Common block for setting up the parts of a form that relate to credit / debit card
624 protected function assignPaymentRelatedVariables() {
626 if ($this->_contactID
) {
627 list($this->userDisplayName
, $this->userEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
628 $this->assign('displayName', $this->userDisplayName
);
631 $this->assignProcessors();
633 $this->assignBillingType();
635 CRM_Core_Payment_Form
::setPaymentFieldsByProcessor($this, $this->_paymentProcessor
, FALSE, TRUE);
638 catch (CRM_Core_Exception
$e) {
639 CRM_Core_Error
::fatal($e->getMessage());
644 * Begin post processing.
646 * This function aims to start to bring together common postProcessing functions.
648 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
649 * access this function.
651 protected function beginPostProcess() {
653 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment(
654 $this->_params
['payment_processor_id'],
655 ($this->_mode
== 'test')
657 if (in_array('credit_card_exp_date', array_keys($this->_params
))) {
658 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
659 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
661 $this->assign('credit_card_exp_date', CRM_Utils_Date
::mysqlToIso(CRM_Utils_Date
::format($this->_params
['credit_card_exp_date'])));
662 $this->assign('credit_card_number',
663 CRM_Utils_System
::mungeCreditCard($this->_params
['credit_card_number'])
665 $this->assign('credit_card_type', CRM_Utils_Array
::value('credit_card_type', $this->_params
));
667 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
672 * Add the billing address to the contact who paid.
674 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
675 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
678 protected function processBillingAddress() {
681 $fields['email-Primary'] = 1;
682 $this->_params
['email-5'] = $this->_params
['email-Primary'] = $this->_contributorEmail
;
683 // now set the values for the billing location.
684 foreach (array_keys($this->_fields
) as $name) {
688 // also add location name to the array
689 $this->_params
["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $this->_params
) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $this->_params
) . ' ' . CRM_Utils_Array
::value('billing_last_name', $this->_params
);
690 $this->_params
["address_name-{$this->_bltID}"] = trim($this->_params
["address_name-{$this->_bltID}"]);
692 $fields["address_name-{$this->_bltID}"] = 1;
694 //ensure we don't over-write the payer's email with the member's email
695 if ($this->_contributorContactID
== $this->_contactID
) {
696 $fields["email-{$this->_bltID}"] = 1;
699 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution
::getPaymentProcessorReadyAddressParams($this->_params
, $this->_bltID
);
700 $nameFields = array('first_name', 'middle_name', 'last_name');
702 foreach ($nameFields as $name) {
704 if (array_key_exists("billing_$name", $this->_params
)) {
705 $this->_params
[$name] = $this->_params
["billing_{$name}"];
706 $this->_params
['preserveDBName'] = TRUE;
710 if ($hasBillingField) {
711 $addressParams = array_merge($this->_params
, $addressParams);
712 //here we are setting up the billing contact - if different from the member they are already created
713 // but they will get billing details assigned
714 CRM_Contact_BAO_Contact
::createProfileContact($addressParams, $fields,
715 $this->_contributorContactID
, NULL, NULL,
716 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type')
719 // Add additional parameters that the payment processors are used to receiving.
720 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
721 $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}"]);
723 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
724 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);