Merge pull request #15584 from civicrm/5.19
[civicrm-core.git] / CRM / Core / Payment.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 useful, 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 use Civi\Payment\System;
29 use Civi\Payment\Exception\PaymentProcessorException;
30
31 /**
32 * Class CRM_Core_Payment.
33 *
34 * This class is the main class for the payment processor subsystem.
35 *
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
38 */
39 abstract class CRM_Core_Payment {
40
41 /**
42 * Component - ie. event or contribute.
43 *
44 * This is used for setting return urls.
45 *
46 * @var string
47 */
48 protected $_component;
49
50 /**
51 * How are we getting billing information.
52 *
53 * We are trying to completely deprecate these parameters.
54 *
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
57 */
58 const
59 BILLING_MODE_FORM = 1,
60 BILLING_MODE_BUTTON = 2,
61 BILLING_MODE_NOTIFY = 4;
62
63 /**
64 * Which payment type(s) are we using?
65 *
66 * credit card
67 * direct debit
68 * or both
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
70 */
71 const
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
75 /**
76 * Subscription / Recurring payment Status
77 * START, END
78 */
79 const
80 RECURRING_PAYMENT_START = 'START',
81 RECURRING_PAYMENT_END = 'END';
82
83 /**
84 * @var object
85 */
86 protected $_paymentProcessor;
87
88 /**
89 * Base url of the calling form (offsite processors).
90 *
91 * @var string
92 */
93 protected $baseReturnUrl;
94
95 /**
96 * Return url upon success (offsite processors).
97 *
98 * @var string
99 */
100 protected $successUrl;
101
102 /**
103 * Return url upon failure (offsite processors).
104 *
105 * @var string
106 */
107 protected $cancelUrl;
108
109 /**
110 * Processor type label.
111 *
112 * (Deprecated parameter but used in some messages).
113 *
114 * @var string
115 * @deprecated
116 *
117 */
118 public $_processorName;
119
120 /**
121 * The profile configured to show on the billing form.
122 *
123 * Currently only the pseudo-profile 'billing' is supported but hopefully in time we will take an id and
124 * load that from the DB and the processor will be able to return a set of fields that combines it's minimum
125 * requirements with the configured requirements.
126 *
127 * Currently only the pseudo-processor 'manual' or 'pay-later' uses this setting to return a 'curated' set
128 * of fields.
129 *
130 * Note this change would probably include converting 'billing' to a reserved profile.
131 *
132 * @var int|string
133 */
134 protected $billingProfile;
135
136 /**
137 * Payment instrument ID.
138 *
139 * This is normally retrieved from the payment_processor table.
140 *
141 * @var int
142 */
143 protected $paymentInstrumentID;
144
145 /**
146 * Is this a back office transaction.
147 *
148 * @var bool
149 */
150 protected $backOffice = FALSE;
151
152 /**
153 * @return bool
154 */
155 public function isBackOffice() {
156 return $this->backOffice;
157 }
158
159 /**
160 * Set back office property.
161 *
162 * @param bool $isBackOffice
163 */
164 public function setBackOffice($isBackOffice) {
165 $this->backOffice = $isBackOffice;
166 }
167
168 /**
169 * Get payment instrument id.
170 *
171 * @return int
172 */
173 public function getPaymentInstrumentID() {
174 return $this->paymentInstrumentID ? $this->paymentInstrumentID : $this->_paymentProcessor['payment_instrument_id'];
175 }
176
177 /**
178 * Getter for the id.
179 *
180 * @return int
181 */
182 public function getID() {
183 return (int) $this->_paymentProcessor['id'];
184 }
185
186 /**
187 * Set payment Instrument id.
188 *
189 * By default we actually ignore the form value. The manual processor takes it more seriously.
190 *
191 * @param int $paymentInstrumentID
192 */
193 public function setPaymentInstrumentID($paymentInstrumentID) {
194 $this->paymentInstrumentID = $this->_paymentProcessor['payment_instrument_id'];
195 }
196
197 /**
198 * Set base return path (offsite processors).
199 *
200 * This is only useful with an internal civicrm form.
201 *
202 * @param string $url
203 * Internal civicrm path.
204 */
205 public function setBaseReturnUrl($url) {
206 $this->baseReturnUrl = $url;
207 }
208
209 /**
210 * Set success return URL (offsite processors).
211 *
212 * This overrides $baseReturnUrl
213 *
214 * @param string $url
215 * Full url of site to return browser to upon success.
216 */
217 public function setSuccessUrl($url) {
218 $this->successUrl = $url;
219 }
220
221 /**
222 * Set cancel return URL (offsite processors).
223 *
224 * This overrides $baseReturnUrl
225 *
226 * @param string $url
227 * Full url of site to return browser to upon failure.
228 */
229 public function setCancelUrl($url) {
230 $this->cancelUrl = $url;
231 }
232
233 /**
234 * Set the configured payment profile.
235 *
236 * @param int|string $value
237 */
238 public function setBillingProfile($value) {
239 $this->billingProfile = $value;
240 }
241
242 /**
243 * Opportunity for the payment processor to override the entire form build.
244 *
245 * @param CRM_Core_Form $form
246 *
247 * @return bool
248 * Should form building stop at this point?
249 */
250 public function buildForm(&$form) {
251 return FALSE;
252 }
253
254 /**
255 * Log payment notification message to forensic system log.
256 *
257 * @todo move to factory class \Civi\Payment\System (or similar)
258 *
259 * @param array $params
260 *
261 * @return mixed
262 */
263 public static function logPaymentNotification($params) {
264 $message = 'payment_notification ';
265 if (!empty($params['processor_name'])) {
266 $message .= 'processor_name=' . $params['processor_name'];
267 }
268 if (!empty($params['processor_id'])) {
269 $message .= 'processor_id=' . $params['processor_id'];
270 }
271
272 $log = new CRM_Utils_SystemLogger();
273 // $_REQUEST doesn't handle JSON, to support providers that POST JSON we need the raw POST data.
274 $rawRequestData = file_get_contents("php://input");
275 if (CRM_Utils_JSON::isValidJSON($rawRequestData)) {
276 $log->alert($message, json_decode($rawRequestData, TRUE));
277 }
278 else {
279 $log->alert($message, $_REQUEST);
280 }
281 }
282
283 /**
284 * Check if capability is supported.
285 *
286 * Capabilities have a one to one relationship with capability-related functions on this class.
287 *
288 * Payment processor classes should over-ride the capability-specific function rather than this one.
289 *
290 * @param string $capability
291 * E.g BackOffice, LiveMode, FutureRecurStartDate.
292 *
293 * @return bool
294 */
295 public function supports($capability) {
296 $function = 'supports' . ucfirst($capability);
297 if (method_exists($this, $function)) {
298 return $this->$function();
299 }
300 return FALSE;
301 }
302
303 /**
304 * Are back office payments supported.
305 *
306 * e.g paypal standard won't permit you to enter a credit card associated
307 * with someone else's login.
308 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
309 * reach a 'stable' point we disable.
310 *
311 * @return bool
312 */
313 protected function supportsBackOffice() {
314 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
315 return FALSE;
316 }
317 else {
318 return TRUE;
319 }
320 }
321
322 /**
323 * Can more than one transaction be processed at once?
324 *
325 * In general processors that process payment by server to server communication support this while others do not.
326 *
327 * In future we are likely to hit an issue where this depends on whether a token already exists.
328 *
329 * @return bool
330 */
331 protected function supportsMultipleConcurrentPayments() {
332 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
333 return FALSE;
334 }
335 else {
336 return TRUE;
337 }
338 }
339
340 /**
341 * Are live payments supported - e.g dummy doesn't support this.
342 *
343 * @return bool
344 */
345 protected function supportsLiveMode() {
346 return TRUE;
347 }
348
349 /**
350 * Are test payments supported.
351 *
352 * @return bool
353 */
354 protected function supportsTestMode() {
355 return TRUE;
356 }
357
358 /**
359 * Does this payment processor support refund?
360 *
361 * @return bool
362 */
363 public function supportsRefund() {
364 return FALSE;
365 }
366
367 /**
368 * Should the first payment date be configurable when setting up back office recurring payments.
369 *
370 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
371 *
372 * @return bool
373 */
374 protected function supportsFutureRecurStartDate() {
375 return FALSE;
376 }
377
378 /**
379 * Does this processor support cancelling recurring contributions through code.
380 *
381 * If the processor returns true it must be possible to take action from within CiviCRM
382 * that will result in no further payments being processed. In the case of token processors (e.g
383 * IATS, eWay) updating the contribution_recur table is probably sufficient.
384 *
385 * @return bool
386 */
387 protected function supportsCancelRecurring() {
388 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
389 }
390
391 /**
392 * Does this processor support pre-approval.
393 *
394 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
395 *
396 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
397 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
398 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
399 *
400 * @return bool
401 */
402 protected function supportsPreApproval() {
403 return FALSE;
404 }
405
406 /**
407 * Does this processor support updating billing info for recurring contributions through code.
408 *
409 * If the processor returns true then it must be possible to update billing info from within CiviCRM
410 * that will be updated at the payment processor.
411 *
412 * @return bool
413 */
414 protected function supportsUpdateSubscriptionBillingInfo() {
415 return method_exists(CRM_Utils_System::getClassName($this), 'updateSubscriptionBillingInfo');
416 }
417
418 /**
419 * Can recurring contributions be set against pledges.
420 *
421 * In practice all processors that use the baseIPN function to finish transactions or
422 * call the completetransaction api support this by looking up previous contributions in the
423 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
424 * adding the new payment to the pledge.
425 *
426 * However, only enabling for processors it has been tested against.
427 *
428 * @return bool
429 */
430 protected function supportsRecurContributionsForPledges() {
431 return FALSE;
432 }
433
434 /**
435 * Function to action pre-approval if supported
436 *
437 * @param array $params
438 * Parameters from the form
439 *
440 * This function returns an array which should contain
441 * - pre_approval_parameters (this will be stored on the calling form & available later)
442 * - redirect_url (if set the browser will be redirected to this.
443 */
444 public function doPreApproval(&$params) {
445 }
446
447 /**
448 * Get any details that may be available to the payment processor due to an approval process having happened.
449 *
450 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
451 * result.
452 *
453 * @param array $storedDetails
454 *
455 * @return array
456 */
457 public function getPreApprovalDetails($storedDetails) {
458 return [];
459 }
460
461 /**
462 * Default payment instrument validation.
463 *
464 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
465 * Not a static function, because I need to check for payment_type.
466 *
467 * @param array $values
468 * @param array $errors
469 */
470 public function validatePaymentInstrument($values, &$errors) {
471 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
472 if ($this->_paymentProcessor['payment_type'] == 1) {
473 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
474 }
475 }
476
477 /**
478 * Getter for the payment processor.
479 *
480 * The payment processor array is based on the civicrm_payment_processor table entry.
481 *
482 * @return array
483 * Payment processor array.
484 */
485 public function getPaymentProcessor() {
486 return $this->_paymentProcessor;
487 }
488
489 /**
490 * Setter for the payment processor.
491 *
492 * @param array $processor
493 */
494 public function setPaymentProcessor($processor) {
495 $this->_paymentProcessor = $processor;
496 }
497
498 /**
499 * Setter for the payment form that wants to use the processor.
500 *
501 * @deprecated
502 *
503 * @param CRM_Core_Form $paymentForm
504 */
505 public function setForm(&$paymentForm) {
506 $this->_paymentForm = $paymentForm;
507 }
508
509 /**
510 * Getter for payment form that is using the processor.
511 * @deprecated
512 * @return CRM_Core_Form
513 * A form object
514 */
515 public function getForm() {
516 return $this->_paymentForm;
517 }
518
519 /**
520 * Get help text information (help, description, etc.) about this payment,
521 * to display to the user.
522 *
523 * @param string $context
524 * Context of the text.
525 * Only explicitly supported contexts are handled without error.
526 * Currently supported:
527 * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
528 *
529 * @param array $params
530 * Parameters for the field, context specific.
531 *
532 * @return string
533 */
534 public function getText($context, $params) {
535 // I have deliberately added a noisy fail here.
536 // The function is intended to be extendable, but not by changes
537 // not documented clearly above.
538 switch ($context) {
539 case 'contributionPageRecurringHelp':
540 // require exactly two parameters
541 if (array_keys($params) == [
542 'is_recur_installments',
543 'is_email_receipt',
544 ]) {
545 $gotText = ts('Your recurring contribution will be processed automatically.');
546 if ($params['is_recur_installments']) {
547 $gotText .= ' ' . ts('You can specify the number of installments, or you can leave the number of installments blank if you want to make an open-ended commitment. In either case, you can choose to cancel at any time.');
548 }
549 if ($params['is_email_receipt']) {
550 $gotText .= ' ' . ts('You will receive an email receipt for each recurring contribution.');
551 }
552 }
553 return $gotText;
554
555 case 'contributionPageContinueText':
556 if ($params['amount'] <= 0) {
557 return ts('To complete this transaction, click the <strong>Continue</strong> button below.');
558 }
559 if ($this->_paymentProcessor['billing_mode'] == 4) {
560 return ts('Click the <strong>Continue</strong> button to go to %1, where you will select your payment method and complete the contribution.', [$this->_paymentProcessor['payment_processor_type']]);
561 }
562 if ($params['is_payment_to_existing']) {
563 return ts('To complete this transaction, click the <strong>Make Payment</strong> button below.');
564 }
565 return ts('To complete your contribution, click the <strong>Continue</strong> button below.');
566
567 }
568 CRM_Core_Error::deprecatedFunctionWarning('Calls to getText must use a supported method');
569 return '';
570 }
571
572 /**
573 * Getter for accessing member vars.
574 *
575 * @todo believe this is unused
576 *
577 * @param string $name
578 *
579 * @return null
580 */
581 public function getVar($name) {
582 return isset($this->$name) ? $this->$name : NULL;
583 }
584
585 /**
586 * Get name for the payment information type.
587 * @todo - use option group + name field (like Omnipay does)
588 * @return string
589 */
590 public function getPaymentTypeName() {
591 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
592 }
593
594 /**
595 * Get label for the payment information type.
596 * @todo - use option group + labels (like Omnipay does)
597 * @return string
598 */
599 public function getPaymentTypeLabel() {
600 return $this->_paymentProcessor['payment_type'] == 1 ? ts('Credit Card') : ts('Direct Debit');
601 }
602
603 /**
604 * Get array of fields that should be displayed on the payment form.
605 *
606 * Common results are
607 * array('credit_card_type', 'credit_card_number', 'cvv2', 'credit_card_exp_date')
608 * or
609 * array('account_holder', 'bank_account_number', 'bank_identification_number', 'bank_name')
610 * or
611 * array()
612 *
613 * @return array
614 * Array of payment fields appropriate to the payment processor.
615 *
616 * @throws CiviCRM_API3_Exception
617 */
618 public function getPaymentFormFields() {
619 if ($this->_paymentProcessor['billing_mode'] == 4) {
620 return [];
621 }
622 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
623 }
624
625 /**
626 * Get an array of the fields that can be edited on the recurring contribution.
627 *
628 * Some payment processors support editing the amount and other scheduling details of recurring payments, especially
629 * those which use tokens. Others are fixed. This function allows the processor to return an array of the fields that
630 * can be updated from the contribution recur edit screen.
631 *
632 * The fields are likely to be a subset of these
633 * - 'amount',
634 * - 'installments',
635 * - 'frequency_interval',
636 * - 'frequency_unit',
637 * - 'cycle_day',
638 * - 'next_sched_contribution_date',
639 * - 'end_date',
640 * - 'failure_retry_day',
641 *
642 * The form does not restrict which fields from the contribution_recur table can be added (although if the html_type
643 * metadata is not defined in the xml for the field it will cause an error.
644 *
645 * Open question - would it make sense to return membership_id in this - which is sometimes editable and is on that
646 * form (UpdateSubscription).
647 *
648 * @return array
649 */
650 public function getEditableRecurringScheduleFields() {
651 if ($this->supports('changeSubscriptionAmount')) {
652 return ['amount'];
653 }
654 return [];
655 }
656
657 /**
658 * Get the help text to present on the recurring update page.
659 *
660 * This should reflect what can or cannot be edited.
661 *
662 * @return string
663 */
664 public function getRecurringScheduleUpdateHelpText() {
665 if (!in_array('amount', $this->getEditableRecurringScheduleFields())) {
666 return ts('Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.');
667 }
668 return ts('Use this form to change the amount or number of installments for this recurring contribution. Changes will be automatically sent to the payment processor. You can not change the contribution frequency.');
669 }
670
671 /**
672 * Get the metadata for all required fields.
673 *
674 * @return array;
675 */
676 protected function getMandatoryFields() {
677 $mandatoryFields = [];
678 foreach ($this->getAllFields() as $field_name => $field_spec) {
679 if (!empty($field_spec['is_required'])) {
680 $mandatoryFields[$field_name] = $field_spec;
681 }
682 }
683 return $mandatoryFields;
684 }
685
686 /**
687 * Get the metadata of all the fields configured for this processor.
688 *
689 * @return array
690 */
691 protected function getAllFields() {
692 $paymentFields = array_intersect_key($this->getPaymentFormFieldsMetadata(), array_flip($this->getPaymentFormFields()));
693 $billingFields = array_intersect_key($this->getBillingAddressFieldsMetadata(), array_flip($this->getBillingAddressFields()));
694 return array_merge($paymentFields, $billingFields);
695 }
696
697 /**
698 * Get array of fields that should be displayed on the payment form for credit cards.
699 *
700 * @return array
701 */
702 protected function getCreditCardFormFields() {
703 return [
704 'credit_card_type',
705 'credit_card_number',
706 'cvv2',
707 'credit_card_exp_date',
708 ];
709 }
710
711 /**
712 * Get array of fields that should be displayed on the payment form for direct debits.
713 *
714 * @return array
715 */
716 protected function getDirectDebitFormFields() {
717 return [
718 'account_holder',
719 'bank_account_number',
720 'bank_identification_number',
721 'bank_name',
722 ];
723 }
724
725 /**
726 * Return an array of all the details about the fields potentially required for payment fields.
727 *
728 * Only those determined by getPaymentFormFields will actually be assigned to the form
729 *
730 * @return array
731 * field metadata
732 */
733 public function getPaymentFormFieldsMetadata() {
734 //@todo convert credit card type into an option value
735 $creditCardType = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::creditCard();
736 $isCVVRequired = Civi::settings()->get('cvv_backoffice_required');
737 if (!$this->isBackOffice()) {
738 $isCVVRequired = TRUE;
739 }
740 return [
741 'credit_card_number' => [
742 'htmlType' => 'text',
743 'name' => 'credit_card_number',
744 'title' => ts('Card Number'),
745 'attributes' => [
746 'size' => 20,
747 'maxlength' => 20,
748 'autocomplete' => 'off',
749 'class' => 'creditcard',
750 ],
751 'is_required' => TRUE,
752 // 'description' => '16 digit card number', // If you enable a description field it will be shown below the field on the form
753 ],
754 'cvv2' => [
755 'htmlType' => 'text',
756 'name' => 'cvv2',
757 'title' => ts('Security Code'),
758 'attributes' => [
759 'size' => 5,
760 'maxlength' => 10,
761 'autocomplete' => 'off',
762 ],
763 'is_required' => $isCVVRequired,
764 'rules' => [
765 [
766 'rule_message' => ts('Please enter a valid value for your card security code. This is usually the last 3-4 digits on the card\'s signature panel.'),
767 'rule_name' => 'integer',
768 'rule_parameters' => NULL,
769 ],
770 ],
771 ],
772 'credit_card_exp_date' => [
773 'htmlType' => 'date',
774 'name' => 'credit_card_exp_date',
775 'title' => ts('Expiration Date'),
776 'attributes' => CRM_Core_SelectValues::date('creditCard'),
777 'is_required' => TRUE,
778 'rules' => [
779 [
780 'rule_message' => ts('Card expiration date cannot be a past date.'),
781 'rule_name' => 'currentDate',
782 'rule_parameters' => TRUE,
783 ],
784 ],
785 'extra' => ['class' => 'crm-form-select'],
786 ],
787 'credit_card_type' => [
788 'htmlType' => 'select',
789 'name' => 'credit_card_type',
790 'title' => ts('Card Type'),
791 'attributes' => $creditCardType,
792 'is_required' => FALSE,
793 ],
794 'account_holder' => [
795 'htmlType' => 'text',
796 'name' => 'account_holder',
797 'title' => ts('Account Holder'),
798 'attributes' => [
799 'size' => 20,
800 'maxlength' => 34,
801 'autocomplete' => 'on',
802 ],
803 'is_required' => TRUE,
804 ],
805 //e.g. IBAN can have maxlength of 34 digits
806 'bank_account_number' => [
807 'htmlType' => 'text',
808 'name' => 'bank_account_number',
809 'title' => ts('Bank Account Number'),
810 'attributes' => [
811 'size' => 20,
812 'maxlength' => 34,
813 'autocomplete' => 'off',
814 ],
815 'rules' => [
816 [
817 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
818 'rule_name' => 'nopunctuation',
819 'rule_parameters' => NULL,
820 ],
821 ],
822 'is_required' => TRUE,
823 ],
824 //e.g. SWIFT-BIC can have maxlength of 11 digits
825 'bank_identification_number' => [
826 'htmlType' => 'text',
827 'name' => 'bank_identification_number',
828 'title' => ts('Bank Identification Number'),
829 'attributes' => [
830 'size' => 20,
831 'maxlength' => 11,
832 'autocomplete' => 'off',
833 ],
834 'is_required' => TRUE,
835 'rules' => [
836 [
837 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
838 'rule_name' => 'nopunctuation',
839 'rule_parameters' => NULL,
840 ],
841 ],
842 ],
843 'bank_name' => [
844 'htmlType' => 'text',
845 'name' => 'bank_name',
846 'title' => ts('Bank Name'),
847 'attributes' => [
848 'size' => 20,
849 'maxlength' => 64,
850 'autocomplete' => 'off',
851 ],
852 'is_required' => TRUE,
853
854 ],
855 'check_number' => [
856 'htmlType' => 'text',
857 'name' => 'check_number',
858 'title' => ts('Check Number'),
859 'is_required' => FALSE,
860 'attributes' => NULL,
861 ],
862 'pan_truncation' => [
863 'htmlType' => 'text',
864 'name' => 'pan_truncation',
865 'title' => ts('Last 4 digits of the card'),
866 'is_required' => FALSE,
867 'attributes' => [
868 'size' => 4,
869 'maxlength' => 4,
870 'minlength' => 4,
871 'autocomplete' => 'off',
872 ],
873 'rules' => [
874 [
875 'rule_message' => ts('Please enter valid last 4 digit card number.'),
876 'rule_name' => 'numeric',
877 'rule_parameters' => NULL,
878 ],
879 ],
880 ],
881 'payment_token' => [
882 'htmlType' => 'hidden',
883 'name' => 'payment_token',
884 'title' => ts('Authorization token'),
885 'is_required' => FALSE,
886 'attributes' => [
887 'size' => 10,
888 'autocomplete' => 'off',
889 'id' => 'payment_token',
890 ],
891 ],
892 ];
893 }
894
895 /**
896 * Get billing fields required for this processor.
897 *
898 * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
899 * alter.
900 *
901 * @param int $billingLocationID
902 *
903 * @return array
904 */
905 public function getBillingAddressFields($billingLocationID = NULL) {
906 if (!$billingLocationID) {
907 // Note that although the billing id is passed around the forms the idea that it would be anything other than
908 // the result of the function below doesn't seem to have eventuated.
909 // So taking this as a param is possibly something to be removed in favour of the standard default.
910 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
911 }
912 if ($this->_paymentProcessor['billing_mode'] != 1 && $this->_paymentProcessor['billing_mode'] != 3) {
913 return [];
914 }
915 return [
916 'first_name' => 'billing_first_name',
917 'middle_name' => 'billing_middle_name',
918 'last_name' => 'billing_last_name',
919 'street_address' => "billing_street_address-{$billingLocationID}",
920 'city' => "billing_city-{$billingLocationID}",
921 'country' => "billing_country_id-{$billingLocationID}",
922 'state_province' => "billing_state_province_id-{$billingLocationID}",
923 'postal_code' => "billing_postal_code-{$billingLocationID}",
924 ];
925 }
926
927 /**
928 * Get form metadata for billing address fields.
929 *
930 * @param int $billingLocationID
931 *
932 * @return array
933 * Array of metadata for address fields.
934 */
935 public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
936 if (!$billingLocationID) {
937 // Note that although the billing id is passed around the forms the idea that it would be anything other than
938 // the result of the function below doesn't seem to have eventuated.
939 // So taking this as a param is possibly something to be removed in favour of the standard default.
940 $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
941 }
942 $metadata = [];
943 $metadata['billing_first_name'] = [
944 'htmlType' => 'text',
945 'name' => 'billing_first_name',
946 'title' => ts('Billing First Name'),
947 'cc_field' => TRUE,
948 'attributes' => [
949 'size' => 30,
950 'maxlength' => 60,
951 'autocomplete' => 'off',
952 ],
953 'is_required' => TRUE,
954 ];
955
956 $metadata['billing_middle_name'] = [
957 'htmlType' => 'text',
958 'name' => 'billing_middle_name',
959 'title' => ts('Billing Middle Name'),
960 'cc_field' => TRUE,
961 'attributes' => [
962 'size' => 30,
963 'maxlength' => 60,
964 'autocomplete' => 'off',
965 ],
966 'is_required' => FALSE,
967 ];
968
969 $metadata['billing_last_name'] = [
970 'htmlType' => 'text',
971 'name' => 'billing_last_name',
972 'title' => ts('Billing Last Name'),
973 'cc_field' => TRUE,
974 'attributes' => [
975 'size' => 30,
976 'maxlength' => 60,
977 'autocomplete' => 'off',
978 ],
979 'is_required' => TRUE,
980 ];
981
982 $metadata["billing_street_address-{$billingLocationID}"] = [
983 'htmlType' => 'text',
984 'name' => "billing_street_address-{$billingLocationID}",
985 'title' => ts('Street Address'),
986 'cc_field' => TRUE,
987 'attributes' => [
988 'size' => 30,
989 'maxlength' => 60,
990 'autocomplete' => 'off',
991 ],
992 'is_required' => TRUE,
993 ];
994
995 $metadata["billing_city-{$billingLocationID}"] = [
996 'htmlType' => 'text',
997 'name' => "billing_city-{$billingLocationID}",
998 'title' => ts('City'),
999 'cc_field' => TRUE,
1000 'attributes' => [
1001 'size' => 30,
1002 'maxlength' => 60,
1003 'autocomplete' => 'off',
1004 ],
1005 'is_required' => TRUE,
1006 ];
1007
1008 $metadata["billing_state_province_id-{$billingLocationID}"] = [
1009 'htmlType' => 'chainSelect',
1010 'title' => ts('State/Province'),
1011 'name' => "billing_state_province_id-{$billingLocationID}",
1012 'cc_field' => TRUE,
1013 'is_required' => TRUE,
1014 ];
1015
1016 $metadata["billing_postal_code-{$billingLocationID}"] = [
1017 'htmlType' => 'text',
1018 'name' => "billing_postal_code-{$billingLocationID}",
1019 'title' => ts('Postal Code'),
1020 'cc_field' => TRUE,
1021 'attributes' => [
1022 'size' => 30,
1023 'maxlength' => 60,
1024 'autocomplete' => 'off',
1025 ],
1026 'is_required' => TRUE,
1027 ];
1028
1029 $metadata["billing_country_id-{$billingLocationID}"] = [
1030 'htmlType' => 'select',
1031 'name' => "billing_country_id-{$billingLocationID}",
1032 'title' => ts('Country'),
1033 'cc_field' => TRUE,
1034 'attributes' => [
1035 '' => ts('- select -'),
1036 ] + CRM_Core_PseudoConstant::country(),
1037 'is_required' => TRUE,
1038 ];
1039 return $metadata;
1040 }
1041
1042 /**
1043 * Get base url dependent on component.
1044 *
1045 * (or preferably set it using the setter function).
1046 *
1047 * @return string
1048 */
1049 protected function getBaseReturnUrl() {
1050 if ($this->baseReturnUrl) {
1051 return $this->baseReturnUrl;
1052 }
1053 if ($this->_component == 'event') {
1054 $baseURL = 'civicrm/event/register';
1055 }
1056 else {
1057 $baseURL = 'civicrm/contribute/transact';
1058 }
1059 return $baseURL;
1060 }
1061
1062 /**
1063 * Get the currency for the transaction.
1064 *
1065 * Handle any inconsistency about how it is passed in here.
1066 *
1067 * @param $params
1068 *
1069 * @return string
1070 */
1071 protected function getCurrency($params) {
1072 return CRM_Utils_Array::value('currencyID', $params, CRM_Utils_Array::value('currency', $params));
1073 }
1074
1075 /**
1076 * Get the currency for the transaction.
1077 *
1078 * Handle any inconsistency about how it is passed in here.
1079 *
1080 * @param $params
1081 *
1082 * @return string
1083 */
1084 protected function getAmount($params) {
1085 return CRM_Utils_Money::format($params['amount'], NULL, NULL, TRUE);
1086 }
1087
1088 /**
1089 * Get url to return to after cancelled or failed transaction.
1090 *
1091 * @param string $qfKey
1092 * @param int $participantID
1093 *
1094 * @return string cancel url
1095 */
1096 public function getCancelUrl($qfKey, $participantID) {
1097 if (isset($this->cancelUrl)) {
1098 return $this->cancelUrl;
1099 }
1100
1101 if ($this->_component == 'event') {
1102 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1103 'reset' => 1,
1104 'cc' => 'fail',
1105 'participantId' => $participantID,
1106 ],
1107 TRUE, NULL, FALSE
1108 );
1109 }
1110
1111 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1112 '_qf_Main_display' => 1,
1113 'qfKey' => $qfKey,
1114 'cancel' => 1,
1115 ],
1116 TRUE, NULL, FALSE
1117 );
1118 }
1119
1120 /**
1121 * Get URL to return the browser to on success.
1122 *
1123 * @param $qfKey
1124 *
1125 * @return string
1126 */
1127 protected function getReturnSuccessUrl($qfKey) {
1128 if (isset($this->successUrl)) {
1129 return $this->successUrl;
1130 }
1131
1132 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1133 '_qf_ThankYou_display' => 1,
1134 'qfKey' => $qfKey,
1135 ],
1136 TRUE, NULL, FALSE
1137 );
1138 }
1139
1140 /**
1141 * Get URL to return the browser to on failure.
1142 *
1143 * @param string $key
1144 * @param int $participantID
1145 * @param int $eventID
1146 *
1147 * @return string
1148 * URL for a failing transactor to be redirected to.
1149 */
1150 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
1151 if (isset($this->cancelUrl)) {
1152 return $this->cancelUrl;
1153 }
1154
1155 $test = $this->_is_test ? '&action=preview' : '';
1156 if ($this->_component == "event") {
1157 return CRM_Utils_System::url('civicrm/event/register',
1158 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
1159 FALSE, NULL, FALSE
1160 );
1161 }
1162 else {
1163 return CRM_Utils_System::url('civicrm/contribute/transact',
1164 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
1165 FALSE, NULL, FALSE
1166 );
1167 }
1168 }
1169
1170 /**
1171 * Get URl for when the back button is pressed.
1172 *
1173 * @param $qfKey
1174 *
1175 * @return string url
1176 */
1177 protected function getGoBackUrl($qfKey) {
1178 return CRM_Utils_System::url($this->getBaseReturnUrl(), [
1179 '_qf_Confirm_display' => 'true',
1180 'qfKey' => $qfKey,
1181 ],
1182 TRUE, NULL, FALSE
1183 );
1184 }
1185
1186 /**
1187 * Get the notify (aka ipn, web hook or silent post) url.
1188 *
1189 * If there is no '.' in it we assume that we are dealing with localhost or
1190 * similar and it is unreachable from the web & hence invalid.
1191 *
1192 * @return string
1193 * URL to notify outcome of transaction.
1194 */
1195 protected function getNotifyUrl() {
1196 $url = CRM_Utils_System::url(
1197 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
1198 [],
1199 TRUE,
1200 NULL,
1201 FALSE,
1202 TRUE
1203 );
1204 return (stristr($url, '.')) ? $url : '';
1205 }
1206
1207 /**
1208 * Calling this from outside the payment subsystem is deprecated - use doPayment.
1209 * @deprecated
1210 * Does a server to server payment transaction.
1211 *
1212 * @param array $params
1213 * Assoc array of input parameters for this transaction.
1214 *
1215 * @return array
1216 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
1217 */
1218 protected function doDirectPayment(&$params) {
1219 return $params;
1220 }
1221
1222 /**
1223 * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
1224 * Any processor that still implements the deprecated doTransferCheckout() or doDirectPayment() should be updated to use doPayment().
1225 *
1226 * This function adds some historical defaults ie. the assumption that if a 'doDirectPayment' processors comes back it completed
1227 * the transaction & in fact doTransferCheckout would not traditionally come back.
1228 * Payment processors should throw exceptions and not return Error objects as they may have done with the old functions.
1229 *
1230 * Payment processors should set payment_status_id (which is really contribution_status_id) in the returned array. The default is assumed to be Pending.
1231 * In some cases the IPN will set the payment to "Completed" some time later.
1232 *
1233 * @fixme Creating a contribution record is inconsistent! We should always create a contribution BEFORE calling doPayment...
1234 * For the current status see: https://lab.civicrm.org/dev/financial/issues/53
1235 * If we DO have a contribution ID, then the payment processor can (and should) update parameters on the contribution record as necessary.
1236 *
1237 * @param array $params
1238 *
1239 * @param string $component
1240 *
1241 * @return array
1242 * Result array (containing at least the key payment_status_id)
1243 *
1244 * @throws \Civi\Payment\Exception\PaymentProcessorException
1245 */
1246 public function doPayment(&$params, $component = 'contribute') {
1247 $this->_component = $component;
1248 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
1249
1250 // If we have a $0 amount, skip call to processor and set payment_status to Completed.
1251 // Conceivably a processor might override this - perhaps for setting up a token - but we don't
1252 // have an example of that at the mome.
1253 if ($params['amount'] == 0) {
1254 $result['payment_status_id'] = array_search('Completed', $statuses);
1255 return $result;
1256 }
1257
1258 if ($this->_paymentProcessor['billing_mode'] == 4) {
1259 $result = $this->doTransferCheckout($params, $component);
1260 if (is_array($result) && !isset($result['payment_status_id'])) {
1261 $result['payment_status_id'] = array_search('Pending', $statuses);
1262 }
1263 }
1264 else {
1265 $result = $this->doDirectPayment($params, $component);
1266 if (is_array($result) && !isset($result['payment_status_id'])) {
1267 if (!empty($params['is_recur'])) {
1268 // See comment block.
1269 $result['payment_status_id'] = array_search('Pending', $statuses);
1270 }
1271 else {
1272 $result['payment_status_id'] = array_search('Completed', $statuses);
1273 }
1274 }
1275 }
1276 if (is_a($result, 'CRM_Core_Error')) {
1277 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
1278 }
1279 return $result;
1280 }
1281
1282 /**
1283 * Refunds payment
1284 *
1285 * Payment processors should set payment_status_id if it set the status to Refunded in case the transaction is successful
1286 *
1287 * @param array $params
1288 *
1289 * @throws \Civi\Payment\Exception\PaymentProcessorException
1290 */
1291 public function doRefund(&$params) {}
1292
1293 /**
1294 * Query payment processor for details about a transaction.
1295 *
1296 * @param array $params
1297 * Array of parameters containing one of:
1298 * - trxn_id Id of an individual transaction.
1299 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
1300 *
1301 * @return array
1302 * Extra parameters retrieved.
1303 * Any parameters retrievable through this should be documented in the function comments at
1304 * CRM_Core_Payment::doQuery. Currently:
1305 * - fee_amount Amount of fee paid
1306 */
1307 public function doQuery($params) {
1308 return [];
1309 }
1310
1311 /**
1312 * This function checks to see if we have the right config values.
1313 *
1314 * @return string
1315 * the error message if any
1316 */
1317 abstract protected function checkConfig();
1318
1319 /**
1320 * Redirect for paypal.
1321 *
1322 * @todo move to paypal class or remove
1323 *
1324 * @param $paymentProcessor
1325 *
1326 * @return bool
1327 */
1328 public static function paypalRedirect(&$paymentProcessor) {
1329 if (!$paymentProcessor) {
1330 return FALSE;
1331 }
1332
1333 if (isset($_GET['payment_date']) &&
1334 isset($_GET['merchant_return_link']) &&
1335 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
1336 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
1337 ) {
1338 return TRUE;
1339 }
1340
1341 return FALSE;
1342 }
1343
1344 /**
1345 * Handle incoming payment notification.
1346 *
1347 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
1348 *
1349 * @todo move to0 \Civi\Payment\System factory method
1350 * Page callback for civicrm/payment/ipn
1351 */
1352 public static function handleIPN() {
1353 try {
1354 self::handlePaymentMethod(
1355 'PaymentNotification',
1356 [
1357 'processor_name' => CRM_Utils_Request::retrieveValue('processor_name', 'String'),
1358 'processor_id' => CRM_Utils_Request::retrieveValue('processor_id', 'Integer'),
1359 'mode' => CRM_Utils_Request::retrieveValue('mode', 'Alphanumeric'),
1360 ]
1361 );
1362 }
1363 catch (CRM_Core_Exception $e) {
1364 Civi::log()->error('ipn_payment_callback_exception', [
1365 'context' => [
1366 'backtrace' => CRM_Core_Error::formatBacktrace(debug_backtrace()),
1367 ],
1368 ]);
1369 }
1370 CRM_Utils_System::civiExit();
1371 }
1372
1373 /**
1374 * Payment callback handler.
1375 *
1376 * The processor_name or processor_id is passed in.
1377 * Note that processor_id is more reliable as one site may have more than one instance of a
1378 * processor & ideally the processor will be validating the results
1379 * Load requested payment processor and call that processor's handle<$method> method
1380 *
1381 * @todo move to \Civi\Payment\System factory method
1382 *
1383 * @param string $method
1384 * 'PaymentNotification' or 'PaymentCron'
1385 * @param array $params
1386 *
1387 * @throws \CRM_Core_Exception
1388 * @throws \Exception
1389 */
1390 public static function handlePaymentMethod($method, $params = []) {
1391 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
1392 $q = explode('/', CRM_Utils_Array::value(CRM_Core_Config::singleton()->userFrameworkURLVar, $_GET, ''));
1393 $lastParam = array_pop($q);
1394 if (is_numeric($lastParam)) {
1395 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
1396 }
1397 else {
1398 self::logPaymentNotification($params);
1399 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
1400 }
1401 }
1402
1403 self::logPaymentNotification($params);
1404
1405 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
1406 FROM civicrm_payment_processor_type ppt
1407 INNER JOIN civicrm_payment_processor pp
1408 ON pp.payment_processor_type_id = ppt.id
1409 AND pp.is_active";
1410
1411 if (isset($params['processor_id'])) {
1412 $sql .= " WHERE pp.id = %2";
1413 $args[2] = [$params['processor_id'], 'Integer'];
1414 $notFound = ts("No active instances of payment processor %1 were found.", [1 => $params['processor_id']]);
1415 }
1416 else {
1417 // This is called when processor_name is passed - passing processor_id instead is recommended.
1418 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
1419 $args[1] = [
1420 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
1421 'Integer',
1422 ];
1423 $args[2] = [$params['processor_name'], 'String'];
1424 $notFound = ts("No active instances of payment processor '%1' were found.", [1 => $params['processor_name']]);
1425 }
1426
1427 $dao = CRM_Core_DAO::executeQuery($sql, $args);
1428
1429 // Check whether we found anything at all.
1430 if (!$dao->N) {
1431 throw new CRM_Core_Exception($notFound);
1432 }
1433
1434 $method = 'handle' . $method;
1435 $extension_instance_found = FALSE;
1436
1437 // In all likelihood, we'll just end up with the one instance returned here. But it's
1438 // possible we may get more. Hence, iterate through all instances ..
1439
1440 while ($dao->fetch()) {
1441 // Check pp is extension - is this still required - surely the singleton below handles it.
1442 $ext = CRM_Extension_System::singleton()->getMapper();
1443 if ($ext->isExtensionKey($dao->class_name)) {
1444 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
1445 require_once $ext->classToPath($paymentClass);
1446 }
1447
1448 $processorInstance = System::singleton()->getById($dao->processor_id);
1449
1450 // Should never be empty - we already established this processor_id exists and is active.
1451 if (empty($processorInstance)) {
1452 continue;
1453 }
1454
1455 // Does PP implement this method, and can we call it?
1456 if (!method_exists($processorInstance, $method) ||
1457 !is_callable([$processorInstance, $method])
1458 ) {
1459 // on the off chance there is a double implementation of this processor we should keep looking for another
1460 // note that passing processor_id is more reliable & we should work to deprecate processor_name
1461 continue;
1462 }
1463
1464 // Everything, it seems, is ok - execute pp callback handler
1465 $processorInstance->$method();
1466 $extension_instance_found = TRUE;
1467 }
1468
1469 // Call IPN postIPNProcess hook to allow for custom processing of IPN data.
1470 $IPNParams = array_merge($_GET, $_REQUEST);
1471 CRM_Utils_Hook::postIPNProcess($IPNParams);
1472 if (!$extension_instance_found) {
1473 $message = "No extension instances of the '%1' payment processor were found.<br />" .
1474 "%2 method is unsupported in legacy payment processors.";
1475 throw new CRM_Core_Exception(ts($message, [
1476 1 => $params['processor_name'],
1477 2 => $method,
1478 ]));
1479 }
1480 }
1481
1482 /**
1483 * Check whether a method is present ( & supported ) by the payment processor object.
1484 *
1485 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
1486 *
1487 * @param string $method
1488 * Method to check for.
1489 *
1490 * @return bool
1491 */
1492 public function isSupported($method) {
1493 return method_exists(CRM_Utils_System::getClassName($this), $method);
1494 }
1495
1496 /**
1497 * Some processors replace the form submit button with their own.
1498 *
1499 * Returning false here will leave the button off front end forms.
1500 *
1501 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
1502 */
1503 public function isSuppressSubmitButtons() {
1504 return FALSE;
1505 }
1506
1507 /**
1508 * Checks to see if invoice_id already exists in db.
1509 *
1510 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
1511 * it is better to standardise to being here.
1512 *
1513 * @param int $invoiceId The ID to check.
1514 *
1515 * @param null $contributionID
1516 * If a contribution exists pass in the contribution ID.
1517 *
1518 * @return bool
1519 * True if invoice ID otherwise exists, else false
1520 */
1521 protected function checkDupe($invoiceId, $contributionID = NULL) {
1522 $contribution = new CRM_Contribute_DAO_Contribution();
1523 $contribution->invoice_id = $invoiceId;
1524 if ($contributionID) {
1525 $contribution->whereAdd("id <> $contributionID");
1526 }
1527 return $contribution->find();
1528 }
1529
1530 /**
1531 * Get url for users to manage this recurring contribution for this processor.
1532 *
1533 * @param int $entityID
1534 * @param null $entity
1535 * @param string $action
1536 *
1537 * @return string
1538 */
1539 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
1540 // Set URL
1541 switch ($action) {
1542 case 'cancel':
1543 if (!$this->supports('cancelRecurring')) {
1544 return NULL;
1545 }
1546 $url = 'civicrm/contribute/unsubscribe';
1547 break;
1548
1549 case 'billing':
1550 //in notify mode don't return the update billing url
1551 if (!$this->supports('updateSubscriptionBillingInfo')) {
1552 return NULL;
1553 }
1554 $url = 'civicrm/contribute/updatebilling';
1555 break;
1556
1557 case 'update':
1558 if (!$this->supports('changeSubscriptionAmount') && !$this->supports('editRecurringContribution')) {
1559 return NULL;
1560 }
1561 $url = 'civicrm/contribute/updaterecur';
1562 break;
1563 }
1564
1565 $userId = CRM_Core_Session::singleton()->get('userID');
1566 $contactID = 0;
1567 $checksumValue = '';
1568 $entityArg = '';
1569
1570 // Find related Contact
1571 if ($entityID) {
1572 switch ($entity) {
1573 case 'membership':
1574 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
1575 $entityArg = 'mid';
1576 break;
1577
1578 case 'contribution':
1579 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
1580 $entityArg = 'coid';
1581 break;
1582
1583 case 'recur':
1584 $sql = "
1585 SELECT DISTINCT con.contact_id
1586 FROM civicrm_contribution_recur rec
1587 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
1588 WHERE rec.id = %1";
1589 $contactID = CRM_Core_DAO::singleValueQuery($sql, [
1590 1 => [
1591 $entityID,
1592 'Integer',
1593 ],
1594 ]);
1595 $entityArg = 'crid';
1596 break;
1597 }
1598 }
1599
1600 // Add entity arguments
1601 if ($entityArg != '') {
1602 // Add checksum argument
1603 if ($contactID != 0 && $userId != $contactID) {
1604 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1605 }
1606 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1607 }
1608
1609 // Else login URL
1610 if ($this->supports('accountLoginURL')) {
1611 return $this->accountLoginURL();
1612 }
1613
1614 // Else default
1615 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
1616 }
1617
1618 /**
1619 * Get description of payment to pass to processor.
1620 *
1621 * This is often what people see in the interface so we want to get
1622 * as much unique information in as possible within the field length (& presumably the early part of the field)
1623 *
1624 * People seeing these can be assumed to be advanced users so quantity of information probably trumps
1625 * having field names to clarify
1626 *
1627 * @param array $params
1628 * @param int $length
1629 *
1630 * @return string
1631 */
1632 protected function getPaymentDescription($params, $length = 24) {
1633 $parts = [
1634 'contactID',
1635 'contributionID',
1636 'description',
1637 'billing_first_name',
1638 'billing_last_name',
1639 ];
1640 $validParts = [];
1641 if (isset($params['description'])) {
1642 $uninformativeStrings = [
1643 ts('Online Event Registration: '),
1644 ts('Online Contribution: '),
1645 ];
1646 $params['description'] = str_replace($uninformativeStrings, '', $params['description']);
1647 }
1648 foreach ($parts as $part) {
1649 if ((!empty($params[$part]))) {
1650 $validParts[] = $params[$part];
1651 }
1652 }
1653 return substr(implode('-', $validParts), 0, $length);
1654 }
1655
1656 /**
1657 * Checks if backoffice recurring edit is allowed
1658 *
1659 * @return bool
1660 */
1661 public function supportsEditRecurringContribution() {
1662 return FALSE;
1663 }
1664
1665 /**
1666 * Does this processor support changing the amount for recurring contributions through code.
1667 *
1668 * If the processor returns true then it must be possible to update the amount from within CiviCRM
1669 * that will be updated at the payment processor.
1670 *
1671 * @return bool
1672 */
1673 protected function supportsChangeSubscriptionAmount() {
1674 return method_exists(CRM_Utils_System::getClassName($this), 'changeSubscriptionAmount');
1675 }
1676
1677 /**
1678 * Checks if payment processor supports recurring contributions
1679 *
1680 * @return bool
1681 */
1682 public function supportsRecurring() {
1683 if (!empty($this->_paymentProcessor['is_recur'])) {
1684 return TRUE;
1685 }
1686 return FALSE;
1687 }
1688
1689 /**
1690 * Checks if payment processor supports an account login URL
1691 * TODO: This is checked by self::subscriptionURL but is only used if no entityID is found.
1692 * TODO: It is implemented by AuthorizeNET, any others?
1693 *
1694 * @return bool
1695 */
1696 protected function supportsAccountLoginURL() {
1697 return method_exists(CRM_Utils_System::getClassName($this), 'accountLoginURL');
1698 }
1699
1700 /**
1701 * Should a receipt be sent out for a pending payment.
1702 *
1703 * e.g for traditional pay later & ones with a delayed settlement a pending receipt makes sense.
1704 */
1705 public function isSendReceiptForPending() {
1706 return FALSE;
1707 }
1708
1709 }