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