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