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