Merge pull request #14667 from hoegrammer/master
[civicrm-core.git] / CRM / Contribute / Form / AbstractEditPayment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * This class generates form components for processing a contribution
803d4bc0 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.
6a488035
TO
30 *
31 */
5b7c9ebc 32class CRM_Contribute_Form_AbstractEditPayment extends CRM_Contact_Form_Task {
a6e29c95 33
34 use CRM_Financial_Form_SalesTaxTrait;
35
6a488035
TO
36 public $_mode;
37
38 public $_action;
39
40 public $_bltID;
41
be2fb01f 42 public $_fields = [];
6a488035 43
a6513ad5 44 /**
5ba7d840 45 * Current payment processor including a copy of the object in 'object' key.
46 *
47 * @var array
a6513ad5 48 */
6a488035 49 public $_paymentProcessor;
7036a6d0
EM
50
51 /**
52 * Available recurring processors.
53 *
54 * @var array
55 */
be2fb01f 56 public $_recurPaymentProcessors = [];
6a488035 57
dc913073 58 /**
100fef9d 59 * Array of processor options in the format id => array($id => $label)
dc913073
EM
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
63 * @var array
64 */
6a488035
TO
65 public $_processors;
66
67 /**
100fef9d 68 * Available payment processors with full details including the key 'object' indexed by their id
dc913073
EM
69 * @var array
70 */
be2fb01f 71 protected $_paymentProcessors = [];
bf4253e7
EM
72
73 /**
74 * Instance of the payment processor object.
75 *
76 * @var CRM_Core_Payment
77 */
78 protected $_paymentObject;
79
c0406a91 80 /**
81 * Entity that $this->_id relates to.
82 *
83 * If set the contact id is not required in the url.
84 *
85 * @var string
86 */
87 protected $entity;
88
6a488035 89 /**
fe482240 90 * The id of the premium that we are proceessing.
6a488035
TO
91 *
92 * @var int
6a488035
TO
93 */
94 public $_premiumID = NULL;
4691b077
EM
95
96 /**
97 * @var CRM_Contribute_DAO_ContributionProduct
98 */
6a488035
TO
99 public $_productDAO = NULL;
100
101 /**
100fef9d 102 * The id of the note
6a488035
TO
103 *
104 * @var int
6a488035
TO
105 */
106 public $_noteID;
107
108 /**
100fef9d 109 * The id of the contact associated with this contribution
6a488035
TO
110 *
111 * @var int
6a488035
TO
112 */
113 public $_contactID;
114
115 /**
100fef9d 116 * The id of the pledge payment that we are processing
6a488035
TO
117 *
118 * @var int
6a488035
TO
119 */
120 public $_ppID;
121
122 /**
100fef9d 123 * The id of the pledge that we are processing
6a488035
TO
124 *
125 * @var int
6a488035
TO
126 */
127 public $_pledgeID;
128
129 /**
100fef9d 130 * Is this contribution associated with an online
6a488035
TO
131 * financial transaction
132 *
b67daa72 133 * @var bool
6a488035
TO
134 */
135 public $_online = FALSE;
136
137 /**
138 * Stores all product option
139 *
140 * @var array
6a488035
TO
141 */
142 public $_options;
143
144 /**
100fef9d 145 * Stores the honor id
6a488035
TO
146 *
147 * @var int
6a488035
TO
148 */
149 public $_honorID = NULL;
150
151 /**
dde5a0ef 152 * Store the financial Type ID
6a488035
TO
153 *
154 * @var array
155 */
156 public $_contributionType;
157
158 /**
159 * The contribution values if an existing contribution
1330f57a 160 * @var array
6a488035
TO
161 */
162 public $_values;
163
164 /**
165 * The pledge values if this contribution is associated with pledge
1330f57a 166 * @var array
6a488035
TO
167 */
168 public $_pledgeValues;
169
170 public $_contributeMode = 'direct';
171
172 public $_context;
173
174 public $_compId;
175
d424ffde 176 /**
6a488035 177 * Store the line items if price set used.
1330f57a 178 * @var array
6a488035
TO
179 */
180 public $_lineItems;
181
0be0b79d
EM
182 /**
183 * Is this a backoffice form
18135422 184 *
0be0b79d
EM
185 * @var bool
186 */
187 public $isBackOffice = TRUE;
188
6a488035 189 protected $_formType;
dde5a0ef 190
18135422 191 /**
192 * Payment instrument id for the transaction.
193 *
194 * @var int
195 */
196 public $paymentInstrumentID;
197
bd4cefac 198 /**
199 * Component - event, membership or contribution.
200 *
201 * @var string
202 */
203 protected $_component;
204
dde5a0ef 205 /**
100fef9d 206 * Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
dde5a0ef
EM
207 * be all in this array in order like
208 * 'credit_card' => array('credit_card_number' ...
209 * 'billing_details' => array('first_name' ...
210 *
211 * such that both the fields and the order can be more easily altered by payment processors & other extensions
212 * @var array
213 */
be2fb01f 214 public $billingFieldSets = [];
dde5a0ef 215
189f0360 216 /**
217 * Monetary fields that may be submitted.
218 *
219 * These should get a standardised format in the beginPostProcess function.
220 *
221 * These fields are common to many forms. Some may override this.
1330f57a 222 * @var array
189f0360 223 */
224 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
225
42e8b05c
EM
226 /**
227 * Pre process function with common actions.
f174ed0b 228 *
229 * @throws \CRM_Core_Exception
230 * @throws \CiviCRM_API3_Exception
42e8b05c
EM
231 */
232 public function preProcess() {
233 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
c0406a91 234 if (empty($this->_contactID) && !empty($this->_id) && $this->entity) {
be2fb01f 235 $this->_contactID = civicrm_api3($this->entity, 'getvalue', ['id' => $this->_id, 'return' => 'contact_id']);
c0406a91 236 }
42e8b05c 237 $this->assign('contactID', $this->_contactID);
be2fb01f 238 CRM_Core_Resources::singleton()->addVars('coreForm', ['contact_id' => (int) $this->_contactID]);
42e8b05c 239 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
19046166 240 $this->_mode = empty($this->_mode) ? CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this) : $this->_mode;
a55e39e9 241 $this->assign('isBackOffice', $this->isBackOffice);
80bb54b2 242 $this->assignContactEmailDetails();
0dc4ef42 243 $this->assignPaymentRelatedVariables();
42e8b05c
EM
244 }
245
186c9c17 246 /**
100fef9d 247 * @param int $id
186c9c17 248 */
d5397f2f
PJ
249 public function showRecordLinkMesssage($id) {
250 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
251 if (CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name') == 'Partially paid') {
252 if ($pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
253 $recordPaymentLink = CRM_Utils_System::url('civicrm/payment',
254 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
255 );
be2fb01f 256 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');
d5397f2f
PJ
257 }
258 }
259 }
260
186c9c17 261 /**
100fef9d 262 * @param int $id
186c9c17
EM
263 * @param $values
264 */
6a488035 265 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
be2fb01f
CW
266 $ids = [];
267 $params = ['id' => $id];
6a488035
TO
268 CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
269
270 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
271 $this->_online = FALSE;
272 $fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
a7488080 273 if (!empty($fids['financialTrxnId'])) {
6a488035
TO
274 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
275 }
eea16664 276
6a488035
TO
277 // Also don't allow user to update some fields for recurring contributions.
278 if (!$this->_online) {
279 $this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
280 }
eea16664 281
6a488035
TO
282 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
283
6a488035
TO
284 //to get note id
285 $daoNote = new CRM_Core_BAO_Note();
286 $daoNote->entity_table = 'civicrm_contribution';
287 $daoNote->entity_id = $id;
288 if ($daoNote->find(TRUE)) {
289 $this->_noteID = $daoNote->id;
290 $values['note'] = $daoNote->note;
291 }
292 $this->_contributionType = $values['financial_type_id'];
6a488035
TO
293 }
294
295 /**
014c4014
TO
296 * @param string $type
297 * Eg 'Contribution'.
6a488035
TO
298 * @param string $subType
299 * @param int $entityId
300 */
301 public function applyCustomData($type, $subType, $entityId) {
302 $this->set('type', $type);
303 $this->set('subType', $subType);
304 $this->set('entityId', $entityId);
305
306 CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
307 CRM_Custom_Form_CustomData::buildQuickForm($this);
308 CRM_Custom_Form_CustomData::setDefaultValues($this);
309 }
310
4691b077 311 /**
100fef9d 312 * @param int $id
4691b077
EM
313 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
314 */
6ea503d4 315 public function assignPremiumProduct($id) {
6a488035
TO
316 $sql = "
317SELECT *
318FROM civicrm_contribution_product
319WHERE contribution_id = {$id}
320";
e03e1641 321 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
322 if ($dao->fetch()) {
323 $this->_premiumID = $dao->id;
324 $this->_productDAO = $dao;
325 }
6a488035
TO
326 }
327
6a488035 328 /**
a6c01b45 329 * @return array
16b10e64 330 * Array of valid processors. The array resembles the DB table but also has 'object' as a key
fbcb6fba
EM
331 * @throws Exception
332 */
333 public function getValidProcessors() {
be2fb01f 334 $capabilities = ['BackOffice'];
52767de0
EM
335 if ($this->_mode) {
336 $capabilities[] = (ucfirst($this->_mode) . 'Mode');
fbcb6fba
EM
337 }
338 $processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
44b6505d
EM
339 return $processors;
340
6a488035
TO
341 }
342
6a488035
TO
343 /**
344 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
345 */
346 public function assignProcessors() {
347 //ensure that processor has a valid config
348 //only valid processors get display to user
be2fb01f 349 $this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(['FutureRecurStartDate']));
18135422 350 $this->_paymentProcessors = $this->getValidProcessors();
351 if (!isset($this->_paymentProcessor['id'])) {
352 // 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
353 $this->_paymentProcessor = reset($this->_paymentProcessors);
354 }
355 if (!$this->_mode) {
356 $this->_paymentProcessor = $this->_paymentProcessors[0];
357 }
be2fb01f
CW
358 elseif (empty($this->_paymentProcessors) || array_keys($this->_paymentProcessors) === [0]) {
359 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]));
18135422 360 }
a58e6d09
JP
361 //Assign submitted processor value if it is different from the loaded one.
362 if (!empty($this->_submitValues['payment_processor_id'])
363 && $this->_paymentProcessor['id'] != $this->_submitValues['payment_processor_id']) {
364 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_submitValues['payment_processor_id']);
365 }
be2fb01f 366 $this->_processors = [];
18135422 367 foreach ($this->_paymentProcessors as $id => $processor) {
95863863
MWMC
368 $this->_processors[$id] = $processor['name'];
369 if (!empty($processor['description'])) {
370 $this->_processors[$id] .= ' : ' . $processor['description'];
371 }
372 if ($processor['is_recur']) {
373 $this->_recurPaymentProcessors[$id] = $this->_processors[$id];
44b6505d 374 }
6a488035 375 }
6c0670d1 376 // CRM-21002: pass the default payment processor ID whose credit card type icons should be populated first
377 CRM_Financial_Form_Payment::addCreditCardJs($this->_paymentProcessor['id']);
18135422 378
6a488035
TO
379 $this->assign('recurringPaymentProcessorIds',
380 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
381 );
382
383 // this required to show billing block
03110609 384 // @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
ebc4703a 385 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
6a488035
TO
386 }
387
186c9c17 388 /**
6ea503d4
TO
389 * Get current currency from DB or use default currency.
390 *
e9bb043a 391 * @param array $submittedValues
186c9c17 392 *
e9bb043a 393 * @return string
186c9c17 394 */
be2fb01f 395 public function getCurrency($submittedValues = []) {
6a488035
TO
396 $config = CRM_Core_Config::singleton();
397
398 $currentCurrency = CRM_Utils_Array::value('currency',
399 $this->_values,
400 $config->defaultCurrency
401 );
402
403 // use submitted currency if present else use current currency
404 $result = CRM_Utils_Array::value('currency',
405 $submittedValues,
406 $currentCurrency
407 );
408 return $result;
409 }
410
6a488035
TO
411 public function preProcessPledge() {
412 //get the payment values associated with given pledge payment id OR check for payments due.
be2fb01f 413 $this->_pledgeValues = [];
6a488035 414 if ($this->_ppID) {
be2fb01f 415 $payParams = ['id' => $this->_ppID];
6a488035
TO
416
417 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
418 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
419 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
420 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
421
422 //get all status
423 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
424 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
425 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
426 }
427
428 //get the pledge values associated with given pledge payment.
429
be2fb01f
CW
430 $ids = [];
431 $pledgeParams = ['id' => $this->_pledgeID];
6a488035
TO
432 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
433 $this->assign('ppID', $this->_ppID);
434 }
435 else {
436 // 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
437 if (isset($this->_contactID)) {
438 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
439
440 if (!empty($contactPledges)) {
441 $payments = $paymentsDue = NULL;
442 $multipleDue = FALSE;
443 foreach ($contactPledges as $key => $pledgeId) {
444 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
445 if ($payments) {
446 if ($paymentsDue) {
447 $multipleDue = TRUE;
448 break;
449 }
450 else {
451 $paymentsDue = $payments;
452 }
453 }
454 }
455 if ($multipleDue) {
456 // Show link to pledge tab since more than one pledge has a payment due
457 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
458 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
459 );
be2fb01f 460 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');
6a488035
TO
461 }
462 elseif ($paymentsDue) {
463 // Show user link to oldest Pending or Overdue pledge payment
464 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
465 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
466 if ($this->_mode) {
467 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
468 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
469 );
470 }
471 else {
472 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
473 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
474 );
475 }
be2fb01f 476 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>.', [
6a488035
TO
477 1 => $ppUrl,
478 2 => $ppAmountDue,
21dfd5f5 479 3 => $ppSchedDate,
be2fb01f 480 ]), ts('Notice'), 'alert');
6a488035
TO
481 }
482 }
483 }
484 }
485 }
486
186c9c17 487 /**
07f8d162 488 * @param array $submittedValues
186c9c17
EM
489 *
490 * @return mixed
491 */
6a488035
TO
492 public function unsetCreditCardFields($submittedValues) {
493 //Offline Contribution.
be2fb01f 494 $unsetParams = [
6a488035
TO
495 'payment_processor_id',
496 "email-{$this->_bltID}",
497 'hidden_buildCreditCard',
498 'hidden_buildDirectDebit',
499 'billing_first_name',
500 'billing_middle_name',
501 'billing_last_name',
502 'street_address-5',
503 "city-{$this->_bltID}",
504 "state_province_id-{$this->_bltID}",
505 "postal_code-{$this->_bltID}",
506 "country_id-{$this->_bltID}",
507 'credit_card_number',
508 'cvv2',
509 'credit_card_exp_date',
510 'credit_card_type',
be2fb01f 511 ];
6a488035
TO
512 foreach ($unsetParams as $key) {
513 if (isset($submittedValues[$key])) {
514 unset($submittedValues[$key]);
515 }
516 }
517 return $submittedValues;
518 }
519
cc984198 520 /**
100fef9d 521 * Common block for setting up the parts of a form that relate to credit / debit card
cc984198
EM
522 */
523 protected function assignPaymentRelatedVariables() {
524 try {
18135422 525 $this->assignProcessors();
526 $this->assignBillingType();
a576ecfa 527 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor, FALSE, TRUE, CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer', $this));
cc984198
EM
528 }
529 catch (CRM_Core_Exception $e) {
a5e16c5d 530 CRM_Core_Error::statusBounce($e->getMessage());
cc984198
EM
531 }
532 }
96025800 533
3b8e6c3f 534 /**
535 * Begin post processing.
536 *
537 * This function aims to start to bring together common postProcessing functions.
538 *
539 * Eventually these are also shared with the front end forms & may need to be moved to where they can also
540 * access this function.
541 */
542 protected function beginPostProcess() {
ba2f3f65 543 if ($this->_mode) {
2c89742a 544 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment(
545 $this->_params['payment_processor_id'],
546 ($this->_mode == 'test')
547 );
ba2f3f65 548 $this->assign('credit_card_exp_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format($this->_params['credit_card_exp_date'])));
b0efa39e 549 $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number']));
275fba6b 550 $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $this->_params));
3b8e6c3f 551 }
3b8e6c3f 552 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
5d3a2b9f 553
a55e39e9 554 self::formatCreditCardDetails($this->_params);
189f0360 555 foreach ($this->submittableMoneyFields as $moneyField) {
556 if (isset($this->_params[$moneyField])) {
557 $this->_params[$moneyField] = CRM_Utils_Rule::cleanMoney($this->_params[$moneyField]);
558 }
559 }
80bb54b2
MWMC
560 if (!empty($this->_params['contact_id']) && empty($this->_contactID)) {
561 // Contact ID has been set in the standalone form.
562 $this->_contactID = $this->_params['contact_id'];
563 $this->assignContactEmailDetails();
564 }
3b8e6c3f 565 }
566
a55e39e9 567 /**
568 * Format credit card details like:
569 * 1. Retrieve last 4 digit from credit card number as pan_truncation
570 * 2. Retrieve credit card type id from name
571 *
572 * @param array $params
573 *
574 * @return void
575 */
576 public static function formatCreditCardDetails(&$params) {
89537f41 577 if (!empty($params['credit_card_type'])) {
a55e39e9 578 $params['card_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $params['credit_card_type']);
579 }
580 if (!empty($params['credit_card_number']) && empty($params['pan_truncation'])) {
581 $params['pan_truncation'] = substr($params['credit_card_number'], -4);
582 }
c79523bb 583 if (!empty($params['credit_card_exp_date'])) {
584 $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
585 $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
586 }
a55e39e9 587 }
3b8e6c3f 588
589 /**
590 * Add the billing address to the contact who paid.
591 *
592 * Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
593 * whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
594 * for pay later.
595 */
596 protected function processBillingAddress() {
be2fb01f 597 $fields = [];
3b8e6c3f 598
599 $fields['email-Primary'] = 1;
600 $this->_params['email-5'] = $this->_params['email-Primary'] = $this->_contributorEmail;
601 // now set the values for the billing location.
602 foreach (array_keys($this->_fields) as $name) {
603 $fields[$name] = 1;
604 }
605
3b8e6c3f 606 $fields["address_name-{$this->_bltID}"] = 1;
607
608 //ensure we don't over-write the payer's email with the member's email
609 if ($this->_contributorContactID == $this->_contactID) {
610 $fields["email-{$this->_bltID}"] = 1;
611 }
612
613 list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($this->_params, $this->_bltID);
bddc8a28 614 $fields = $this->formatParamsForPaymentProcessor($fields);
3b8e6c3f 615
616 if ($hasBillingField) {
617 $addressParams = array_merge($this->_params, $addressParams);
dc0ca56c
ML
618 // CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
619 // Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
620 // Note this source field is covered by a unit test.
621 if (isset($addressParams['source'])) {
622 unset($addressParams['source']);
623 }
3b8e6c3f 624 //here we are setting up the billing contact - if different from the member they are already created
625 // but they will get billing details assigned
626 CRM_Contact_BAO_Contact::createProfileContact($addressParams, $fields,
627 $this->_contributorContactID, NULL, NULL,
628 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')
629 );
630 }
23cb875c 631
632 $this->assignBillingName($this->_params);
3b8e6c3f 633 }
634
44032b26 635 /**
636 * Get default values for billing fields.
637 *
638 * @todo this function still replicates code in several other places in the code.
639 *
640 * Also - the call to getProfileDefaults possibly covers the state_province & country already.
641 *
642 * @param $defaults
643 *
644 * @return array
645 */
646 protected function getBillingDefaults($defaults) {
647 // set default country from config if no country set
648 $config = CRM_Core_Config::singleton();
649 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
650 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
651 }
652
653 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
654 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
655 }
656
657 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
658 return array_merge($defaults, $billingDefaults);
659 }
660
0dc4ef42 661 /**
662 * Get the default payment instrument id.
663 *
664 * @return int
665 */
666 protected function getDefaultPaymentInstrumentId() {
667 $paymentInstrumentID = CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer');
668 if ($paymentInstrumentID) {
669 return $paymentInstrumentID;
670 }
671 return key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
672 }
673
b15c60e1 674 /**
675 * Add the payment processor select to the form.
676 *
677 * @param bool $isRequired
678 * Is it a mandatory field.
679 * @param bool $isBuildRecurBlock
680 * True if we want to build recur on change
681 * @param bool $isBuildAutoRenewBlock
682 * True if we want to build autorenew on change.
683 */
684 protected function addPaymentProcessorSelect($isRequired, $isBuildRecurBlock = FALSE, $isBuildAutoRenewBlock = FALSE) {
685 if (!$this->_mode) {
686 return;
687 }
be2fb01f 688 $js = ($isBuildRecurBlock ? ['onChange' => "buildRecurBlock( this.value ); return false;"] : NULL);
b15c60e1 689 if ($isBuildAutoRenewBlock) {
be2fb01f 690 $js = ['onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');"];
b15c60e1 691 }
692 $element = $this->add('select',
693 'payment_processor_id',
694 ts('Payment Processor'),
be2fb01f 695 array_diff_key($this->_processors, [0 => 1]),
b15c60e1 696 $isRequired,
697 $js
698 );
699 // The concept of _online is not really explained & the code is old
700 // @todo figure out & document.
701 if ($this->_online) {
702 $element->freeze();
703 }
704 }
705
c0406a91 706 /**
707 * Assign the values to build the payment info block.
708 *
1330f57a 709 * @return string
c0406a91 710 * Block title.
711 */
712 protected function assignPaymentInfoBlock() {
713 $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, TRUE);
714 $title = ts('View Payment');
715 if (!empty($this->_component) && $this->_component == 'event') {
716 $info = CRM_Event_BAO_Participant::participantDetails($this->_id);
717 $title .= " - {$info['title']}";
718 }
719 $this->assign('transaction', TRUE);
720 $this->assign('payments', $paymentInfo['transaction']);
721 $this->assign('paymentLinks', $paymentInfo['payment_links']);
722 return $title;
723 }
724
80bb54b2
MWMC
725 protected function assignContactEmailDetails() {
726 if ($this->_contactID) {
727 list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
a94b009a
MWMC
728 if (empty($this->userDisplayName)) {
729 $this->userDisplayName = civicrm_api3('contact', 'getvalue', ['id' => $this->_contactID, 'return' => 'display_name']);
730 }
80bb54b2
MWMC
731 $this->assign('displayName', $this->userDisplayName);
732 }
733 }
734
6a488035 735}