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