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