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