CRM-16808 follow up - paypal express being validated as paypal pro
[civicrm-core.git] / CRM / Core / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\System;
29 use Civi\Payment\Exception\PaymentProcessorException;
30
31 /**
32 * Class CRM_Core_Payment.
33 *
34 * This class is the main class for the payment processor subsystem.
35 *
36 * It is the parent class for payment processors. It also holds some IPN related functions
37 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
38 */
39 abstract class CRM_Core_Payment {
40
41 /**
42 * Component - ie. event or contribute.
43 *
44 * This is used for setting return urls.
45 *
46 * @var string
47 */
48 protected $_component;
49
50 /**
51 * How are we getting billing information.
52 *
53 * We are trying to completely deprecate these parameters.
54 *
55 * FORM - we collect it on the same page
56 * BUTTON - the processor collects it and sends it back to us via some protocol
57 */
58 const
59 BILLING_MODE_FORM = 1,
60 BILLING_MODE_BUTTON = 2,
61 BILLING_MODE_NOTIFY = 4;
62
63 /**
64 * Which payment type(s) are we using?
65 *
66 * credit card
67 * direct debit
68 * or both
69 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
70 */
71 const
72 PAYMENT_TYPE_CREDIT_CARD = 1,
73 PAYMENT_TYPE_DIRECT_DEBIT = 2;
74
75 /**
76 * Subscription / Recurring payment Status
77 * START, END
78 */
79 const
80 RECURRING_PAYMENT_START = 'START',
81 RECURRING_PAYMENT_END = 'END';
82
83 protected $_paymentProcessor;
84
85 /**
86 * Opportunity for the payment processor to override the entire form build.
87 *
88 * @param CRM_Core_Form $form
89 *
90 * @return bool
91 * Should form building stop at this point?
92 */
93 public function buildForm(&$form) {
94 return FALSE;
95 }
96
97 /**
98 * Log payment notification message to forensic system log.
99 *
100 * @todo move to factory class \Civi\Payment\System (or similar)
101 *
102 * @param array $params
103 *
104 * @return mixed
105 */
106 public static function logPaymentNotification($params) {
107 $message = 'payment_notification ';
108 if (!empty($params['processor_name'])) {
109 $message .= 'processor_name=' . $params['processor_name'];
110 }
111 if (!empty($params['processor_id'])) {
112 $message .= 'processor_id=' . $params['processor_id'];
113 }
114
115 $log = new CRM_Utils_SystemLogger();
116 $log->alert($message, $_REQUEST);
117 }
118
119 /**
120 * Check if capability is supported.
121 *
122 * Capabilities have a one to one relationship with capability-related functions on this class.
123 *
124 * Payment processor classes should over-ride the capability-specific function rather than this one.
125 *
126 * @param string $capability
127 * E.g BackOffice, LiveMode, FutureRecurStartDate.
128 *
129 * @return bool
130 */
131 public function supports($capability) {
132 $function = 'supports' . ucfirst($capability);
133 if (method_exists($this, $function)) {
134 return $this->$function();
135 }
136 return FALSE;
137 }
138
139 /**
140 * Are back office payments supported.
141 *
142 * e.g paypal standard won't permit you to enter a credit card associated
143 * with someone else's login.
144 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
145 * reach a 'stable' point we disable.
146 *
147 * @return bool
148 */
149 protected function supportsBackOffice() {
150 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
151 return FALSE;
152 }
153 else {
154 return TRUE;
155 }
156 }
157
158 /**
159 * Can more than one transaction be processed at once?
160 *
161 * In general processors that process payment by server to server communication support this while others do not.
162 *
163 * In future we are likely to hit an issue where this depends on whether a token already exists.
164 *
165 * @return bool
166 */
167 protected function supportsMultipleConcurrentPayments() {
168 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
169 return FALSE;
170 }
171 else {
172 return TRUE;
173 }
174 }
175
176 /**
177 * Are live payments supported - e.g dummy doesn't support this.
178 *
179 * @return bool
180 */
181 protected function supportsLiveMode() {
182 return TRUE;
183 }
184
185 /**
186 * Are test payments supported.
187 *
188 * @return bool
189 */
190 protected function supportsTestMode() {
191 return TRUE;
192 }
193
194 /**
195 * Should the first payment date be configurable when setting up back office recurring payments.
196 *
197 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
198 *
199 * @return bool
200 */
201 protected function supportsFutureRecurStartDate() {
202 return FALSE;
203 }
204
205 /**
206 * Does this processor support cancelling recurring contributions through code.
207 *
208 * @return bool
209 */
210 protected function supportsCancelRecurring() {
211 return method_exists(CRM_Utils_System::getClassName($this), 'cancelSubscription');
212 }
213
214 /**
215 * Does this processor support pre-approval.
216 *
217 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
218 *
219 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
220 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
221 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
222 *
223 * @return bool
224 */
225 protected function supportsPreApproval() {
226 return FALSE;
227 }
228
229 /**
230 * Can recurring contributions be set against pledges.
231 *
232 * In practice all processors that use the baseIPN function to finish transactions or
233 * call the completetransaction api support this by looking up previous contributions in the
234 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
235 * adding the new payment to the pledge.
236 *
237 * However, only enabling for processors it has been tested against.
238 *
239 * @return bool
240 */
241 protected function supportsRecurContributionsForPledges() {
242 return FALSE;
243 }
244
245 /**
246 * Function to action pre-approval if supported
247 *
248 * @param array $params
249 * Parameters from the form
250 *
251 * This function returns an array which should contain
252 * - pre_approval_parameters (this will be stored on the calling form & available later)
253 * - redirect_url (if set the browser will be redirected to this.
254 */
255 public function doPreApproval(&$params) {}
256
257 /**
258 * Get any details that may be available to the payment processor due to an approval process having happened.
259 *
260 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
261 * result.
262 *
263 * @param array $storedDetails
264 *
265 * @return array
266 */
267 public function getPreApprovalDetails($storedDetails) {
268 return array();
269 }
270
271 /**
272 * Default payment instrument validation.
273 *
274 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
275 * Not a static function, because I need to check for payment_type.
276 *
277 * @param array $values
278 * @param array $errors
279 */
280 public function validatePaymentInstrument($values, &$errors) {
281 if ($this->_paymentProcessor['payment_type'] == 1) {
282 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
283 }
284 }
285
286 /**
287 * Getter for the payment processor.
288 *
289 * The payment processor array is based on the civicrm_payment_processor table entry.
290 *
291 * @return array
292 * Payment processor array.
293 */
294 public function getPaymentProcessor() {
295 return $this->_paymentProcessor;
296 }
297
298 /**
299 * Setter for the payment processor.
300 *
301 * @param array $processor
302 */
303 public function setPaymentProcessor($processor) {
304 $this->_paymentProcessor = $processor;
305 }
306
307 /**
308 * Setter for the payment form that wants to use the processor.
309 *
310 * @deprecated
311 *
312 * @param CRM_Core_Form $paymentForm
313 */
314 public function setForm(&$paymentForm) {
315 $this->_paymentForm = $paymentForm;
316 }
317
318 /**
319 * Getter for payment form that is using the processor.
320 * @deprecated
321 * @return CRM_Core_Form
322 * A form object
323 */
324 public function getForm() {
325 return $this->_paymentForm;
326 }
327
328 /**
329 * Getter for accessing member vars.
330 *
331 * @todo believe this is unused
332 *
333 * @param string $name
334 *
335 * @return null
336 */
337 public function getVar($name) {
338 return isset($this->$name) ? $this->$name : NULL;
339 }
340
341 /**
342 * Get name for the payment information type.
343 * @todo - use option group + name field (like Omnipay does)
344 * @return string
345 */
346 public function getPaymentTypeName() {
347 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
348 }
349
350 /**
351 * Get label for the payment information type.
352 * @todo - use option group + labels (like Omnipay does)
353 * @return string
354 */
355 public function getPaymentTypeLabel() {
356 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
357 }
358
359 /**
360 * Get array of fields that should be displayed on the payment form.
361 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
362 * @return array
363 * @throws CiviCRM_API3_Exception
364 */
365 public function getPaymentFormFields() {
366 if ($this->_paymentProcessor['billing_mode'] == 4) {
367 return array();
368 }
369 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
370 }
371
372 /**
373 * Get array of fields that should be displayed on the payment form for credit cards.
374 *
375 * @return array
376 */
377 protected function getCreditCardFormFields() {
378 return array(
379 'credit_card_type',
380 'credit_card_number',
381 'cvv2',
382 'credit_card_exp_date',
383 );
384 }
385
386 /**
387 * Get array of fields that should be displayed on the payment form for direct debits.
388 *
389 * @return array
390 */
391 protected function getDirectDebitFormFields() {
392 return array(
393 'account_holder',
394 'bank_account_number',
395 'bank_identification_number',
396 'bank_name',
397 );
398 }
399
400 /**
401 * Return an array of all the details about the fields potentially required for payment fields.
402 *
403 * Only those determined by getPaymentFormFields will actually be assigned to the form
404 *
405 * @return array
406 * field metadata
407 */
408 public function getPaymentFormFieldsMetadata() {
409 //@todo convert credit card type into an option value
410 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
411 return array(
412 'credit_card_number' => array(
413 'htmlType' => 'text',
414 'name' => 'credit_card_number',
415 'title' => ts('Card Number'),
416 'cc_field' => TRUE,
417 'attributes' => array(
418 'size' => 20,
419 'maxlength' => 20,
420 'autocomplete' => 'off',
421 'class' => 'creditcard',
422 ),
423 'is_required' => TRUE,
424 ),
425 'cvv2' => array(
426 'htmlType' => 'text',
427 'name' => 'cvv2',
428 'title' => ts('Security Code'),
429 'cc_field' => TRUE,
430 'attributes' => array(
431 'size' => 5,
432 'maxlength' => 10,
433 'autocomplete' => 'off',
434 ),
435 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
436 'cvv_backoffice_required',
437 NULL,
438 1
439 ),
440 'rules' => array(
441 array(
442 '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.'),
443 'rule_name' => 'integer',
444 'rule_parameters' => NULL,
445 ),
446 ),
447 ),
448 'credit_card_exp_date' => array(
449 'htmlType' => 'date',
450 'name' => 'credit_card_exp_date',
451 'title' => ts('Expiration Date'),
452 'cc_field' => TRUE,
453 'attributes' => CRM_Core_SelectValues::date('creditCard'),
454 'is_required' => TRUE,
455 'rules' => array(
456 array(
457 'rule_message' => ts('Card expiration date cannot be a past date.'),
458 'rule_name' => 'currentDate',
459 'rule_parameters' => TRUE,
460 ),
461 ),
462 ),
463 'credit_card_type' => array(
464 'htmlType' => 'select',
465 'name' => 'credit_card_type',
466 'title' => ts('Card Type'),
467 'cc_field' => TRUE,
468 'attributes' => $creditCardType,
469 'is_required' => FALSE,
470 ),
471 'account_holder' => array(
472 'htmlType' => 'text',
473 'name' => 'account_holder',
474 'title' => ts('Account Holder'),
475 'cc_field' => TRUE,
476 'attributes' => array(
477 'size' => 20,
478 'maxlength' => 34,
479 'autocomplete' => 'on',
480 ),
481 'is_required' => TRUE,
482 ),
483 //e.g. IBAN can have maxlength of 34 digits
484 'bank_account_number' => array(
485 'htmlType' => 'text',
486 'name' => 'bank_account_number',
487 'title' => ts('Bank Account Number'),
488 'cc_field' => TRUE,
489 'attributes' => array(
490 'size' => 20,
491 'maxlength' => 34,
492 'autocomplete' => 'off',
493 ),
494 'rules' => array(
495 array(
496 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
497 'rule_name' => 'nopunctuation',
498 'rule_parameters' => NULL,
499 ),
500 ),
501 'is_required' => TRUE,
502 ),
503 //e.g. SWIFT-BIC can have maxlength of 11 digits
504 'bank_identification_number' => array(
505 'htmlType' => 'text',
506 'name' => 'bank_identification_number',
507 'title' => ts('Bank Identification Number'),
508 'cc_field' => TRUE,
509 'attributes' => array(
510 'size' => 20,
511 'maxlength' => 11,
512 'autocomplete' => 'off',
513 ),
514 'is_required' => TRUE,
515 'rules' => array(
516 array(
517 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
518 'rule_name' => 'nopunctuation',
519 'rule_parameters' => NULL,
520 ),
521 ),
522 ),
523 'bank_name' => array(
524 'htmlType' => 'text',
525 'name' => 'bank_name',
526 'title' => ts('Bank Name'),
527 'cc_field' => TRUE,
528 'attributes' => array(
529 'size' => 20,
530 'maxlength' => 64,
531 'autocomplete' => 'off',
532 ),
533 'is_required' => TRUE,
534
535 ),
536 );
537 }
538
539 /**
540 * Get base url dependent on component.
541 *
542 * @return string|void
543 */
544 protected function getBaseReturnUrl() {
545 if ($this->_component == 'event') {
546 $baseURL = 'civicrm/event/register';
547 }
548 else {
549 $baseURL = 'civicrm/contribute/transact';
550 }
551 return $baseURL;
552 }
553
554 /**
555 * Get url to return to after cancelled or failed transaction
556 *
557 * @param $qfKey
558 * @param $participantID
559 *
560 * @return string cancel url
561 */
562 protected function getCancelUrl($qfKey, $participantID) {
563 if ($this->_component == 'event') {
564 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
565 'reset' => 1,
566 'cc' => 'fail',
567 'participantId' => $participantID,
568 ),
569 TRUE, NULL, FALSE
570 );
571 }
572
573 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
574 '_qf_Main_display' => 1,
575 'qfKey' => $qfKey,
576 'cancel' => 1,
577 ),
578 TRUE, NULL, FALSE
579 );
580 }
581
582 /**
583 * Get URL to return the browser to on success.
584 *
585 * @param $qfKey
586 *
587 * @return string
588 */
589 protected function getReturnSuccessUrl($qfKey) {
590 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
591 '_qf_ThankYou_display' => 1,
592 'qfKey' => $qfKey,
593 ),
594 TRUE, NULL, FALSE
595 );
596 }
597
598 /**
599 * Get URL to return the browser to on failure.
600 *
601 * @param string $key
602 * @param int $participantID
603 * @param int $eventID
604 *
605 * @return string
606 * URL for a failing transactor to be redirected to.
607 */
608 protected function getReturnFailUrl($key, $participantID = NULL, $eventID = NULL) {
609 $test = $this->_is_test ? '&action=preview' : '';
610 if ($this->_component == "event") {
611 return CRM_Utils_System::url('civicrm/event/register',
612 "reset=1&cc=fail&participantId={$participantID}&id={$eventID}{$test}&qfKey={$key}",
613 FALSE, NULL, FALSE
614 );
615 }
616 else {
617 return CRM_Utils_System::url('civicrm/contribute/transact',
618 "_qf_Main_display=1&cancel=1&qfKey={$key}{$test}",
619 FALSE, NULL, FALSE
620 );
621 }
622 }
623
624 /**
625 * Get URl for when the back button is pressed.
626 *
627 * @param $qfKey
628 *
629 * @return string url
630 */
631 protected function getGoBackUrl($qfKey) {
632 return CRM_Utils_System::url($this->getBaseReturnUrl(), array(
633 '_qf_Confirm_display' => 'true',
634 'qfKey' => $qfKey,
635 ),
636 TRUE, NULL, FALSE
637 );
638 }
639
640 /**
641 * Get the notify (aka ipn, web hook or silent post) url.
642 *
643 * If there is no '.' in it we assume that we are dealing with localhost or
644 * similar and it is unreachable from the web & hence invalid.
645 *
646 * @return string
647 * URL to notify outcome of transaction.
648 */
649 protected function getNotifyUrl() {
650 $url = CRM_Utils_System::url(
651 'civicrm/payment/ipn/' . $this->_paymentProcessor['id'],
652 array(),
653 TRUE
654 );
655 return (stristr($url, '.')) ? $url : '';
656 }
657
658 /**
659 * Calling this from outside the payment subsystem is deprecated - use doPayment.
660 *
661 * Does a server to server payment transaction.
662 *
663 * @param array $params
664 * Assoc array of input parameters for this transaction.
665 *
666 * @return array
667 * the result in an nice formatted array (or an error object - but throwing exceptions is preferred)
668 */
669 protected function doDirectPayment(&$params) {
670 return $params;
671 }
672
673 /**
674 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
675 *
676 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
677 * more agnostic.
678 *
679 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
680 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
681 * doTransferCheckout would not traditionally come back.
682 *
683 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
684 * to be Pending.
685 *
686 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
687 * return Error objects
688 *
689 * @param array $params
690 *
691 * @param string $component
692 *
693 * @return array
694 * Result array
695 *
696 * @throws \Civi\Payment\Exception\PaymentProcessorException
697 */
698 public function doPayment(&$params, $component = 'contribute') {
699 $this->_component = $component;
700 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
701 if ($this->_paymentProcessor['billing_mode'] == 4) {
702 $result = $this->doTransferCheckout($params, $component);
703 if (is_array($result) && !isset($result['payment_status_id'])) {
704 $result['payment_status_id'] = array_search('Pending', $statuses);
705 }
706 }
707 else {
708 if ($this->_paymentProcessor['billing_mode'] == 1) {
709 $result = $this->doDirectPayment($params, $component);
710 }
711 else {
712 $result = $this->doExpressCheckout($params);
713 }
714 if (is_array($result) && !isset($result['payment_status_id'])) {
715 if (!empty($params['is_recur'])) {
716 // See comment block.
717 $result['payment_status_id'] = array_search('Pending', $statuses);
718 }
719 else {
720 $result['payment_status_id'] = array_search('Completed', $statuses);
721 }
722 }
723 }
724 if (is_a($result, 'CRM_Core_Error')) {
725 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
726 }
727 return $result;
728 }
729
730 /**
731 * This function checks to see if we have the right config values.
732 *
733 * @return string
734 * the error message if any
735 */
736 abstract protected function checkConfig();
737
738 /**
739 * Redirect for paypal.
740 *
741 * @todo move to paypal class or remove
742 *
743 * @param $paymentProcessor
744 *
745 * @return bool
746 */
747 public static function paypalRedirect(&$paymentProcessor) {
748 if (!$paymentProcessor) {
749 return FALSE;
750 }
751
752 if (isset($_GET['payment_date']) &&
753 isset($_GET['merchant_return_link']) &&
754 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
755 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
756 ) {
757 return TRUE;
758 }
759
760 return FALSE;
761 }
762
763 /**
764 * Handle incoming payment notification.
765 *
766 * IPNs, also called silent posts are notifications of payment outcomes or activity on an external site.
767 *
768 * @todo move to0 \Civi\Payment\System factory method
769 * Page callback for civicrm/payment/ipn
770 */
771 public static function handleIPN() {
772 self::handlePaymentMethod(
773 'PaymentNotification',
774 array(
775 'processor_name' => @$_GET['processor_name'],
776 'processor_id' => @$_GET['processor_id'],
777 'mode' => @$_GET['mode'],
778 'q' => @$_GET['q'],
779 )
780 );
781 CRM_Utils_System::civiExit();
782 }
783
784 /**
785 * Payment callback handler.
786 *
787 * The processor_name or processor_id is passed in.
788 * Note that processor_id is more reliable as one site may have more than one instance of a
789 * processor & ideally the processor will be validating the results
790 * Load requested payment processor and call that processor's handle<$method> method
791 *
792 * @todo move to \Civi\Payment\System factory method
793 *
794 * @param string $method
795 * 'PaymentNotification' or 'PaymentCron'
796 * @param array $params
797 *
798 * @throws \CRM_Core_Exception
799 * @throws \Exception
800 */
801 public static function handlePaymentMethod($method, $params = array()) {
802 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
803 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
804 $lastParam = array_pop($q);
805 if (is_numeric($lastParam)) {
806 $params['processor_id'] = $_GET['processor_id'] = $lastParam;
807 }
808 else {
809 throw new CRM_Core_Exception("Either 'processor_id' (recommended) or 'processor_name' (deprecated) is required for payment callback.");
810 }
811 }
812
813 self::logPaymentNotification($params);
814
815 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
816 FROM civicrm_payment_processor_type ppt
817 INNER JOIN civicrm_payment_processor pp
818 ON pp.payment_processor_type_id = ppt.id
819 AND pp.is_active";
820
821 if (isset($params['processor_id'])) {
822 $sql .= " WHERE pp.id = %2";
823 $args[2] = array($params['processor_id'], 'Integer');
824 $notFound = ts("No active instances of payment processor %1 were found.", array(1 => $params['processor_id']));
825 }
826 else {
827 // This is called when processor_name is passed - passing processor_id instead is recommended.
828 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
829 $args[1] = array(
830 (CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0,
831 'Integer',
832 );
833 $args[2] = array($params['processor_name'], 'String');
834 $notFound = ts("No active instances of payment processor '%1' were found.", array(1 => $params['processor_name']));
835 }
836
837 $dao = CRM_Core_DAO::executeQuery($sql, $args);
838
839 // Check whether we found anything at all.
840 if (!$dao->N) {
841 CRM_Core_Error::fatal($notFound);
842 }
843
844 $method = 'handle' . $method;
845 $extension_instance_found = FALSE;
846
847 // In all likelihood, we'll just end up with the one instance returned here. But it's
848 // possible we may get more. Hence, iterate through all instances ..
849
850 while ($dao->fetch()) {
851 // Check pp is extension - is this still required - surely the singleton below handles it.
852 $ext = CRM_Extension_System::singleton()->getMapper();
853 if ($ext->isExtensionKey($dao->class_name)) {
854 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
855 require_once $ext->classToPath($paymentClass);
856 }
857
858 $processorInstance = Civi\Payment\System::singleton()->getById($dao->processor_id);
859
860 // Should never be empty - we already established this processor_id exists and is active.
861 if (empty($processorInstance)) {
862 continue;
863 }
864
865 // Does PP implement this method, and can we call it?
866 if (!method_exists($processorInstance, $method) ||
867 !is_callable(array($processorInstance, $method))
868 ) {
869 // on the off chance there is a double implementation of this processor we should keep looking for another
870 // note that passing processor_id is more reliable & we should work to deprecate processor_name
871 continue;
872 }
873
874 // Everything, it seems, is ok - execute pp callback handler
875 $processorInstance->$method();
876 $extension_instance_found = TRUE;
877 }
878
879 if (!$extension_instance_found) {
880 $message = "No extension instances of the '%1' payment processor were found.<br />" .
881 "%2 method is unsupported in legacy payment processors.";
882 CRM_Core_Error::fatal(ts($message, array(1 => $params['processor_name'], 2 => $method)));
883 }
884 }
885
886 /**
887 * Check whether a method is present ( & supported ) by the payment processor object.
888 *
889 * @deprecated - use $paymentProcessor->supports(array('cancelRecurring');
890 *
891 * @param string $method
892 * Method to check for.
893 *
894 * @return bool
895 */
896 public function isSupported($method = 'cancelSubscription') {
897 return method_exists(CRM_Utils_System::getClassName($this), $method);
898 }
899
900 /**
901 * Some processors replace the form submit button with their own.
902 *
903 * Returning false here will leave the button off front end forms.
904 *
905 * At this stage there is zero cross-over between back-office processors and processors that suppress the submit.
906 */
907 public function isSuppressSubmitButtons() {
908 return FALSE;
909 }
910
911 /**
912 * Checks to see if invoice_id already exists in db.
913 *
914 * It's arguable if this belongs in the payment subsystem at all but since several processors implement it
915 * it is better to standardise to being here.
916 *
917 * @param int $invoiceId The ID to check.
918 *
919 * @param null $contributionID
920 * If a contribution exists pass in the contribution ID.
921 *
922 * @return bool
923 * True if invoice ID otherwise exists, else false
924 */
925 protected function checkDupe($invoiceId, $contributionID = NULL) {
926 $contribution = new CRM_Contribute_DAO_Contribution();
927 $contribution->invoice_id = $invoiceId;
928 if ($contributionID) {
929 $contribution->whereAdd("id <> $contributionID");
930 }
931 return $contribution->find();
932 }
933
934 /**
935 * Get url for users to manage this recurring contribution for this processor.
936 *
937 * @param int $entityID
938 * @param null $entity
939 * @param string $action
940 *
941 * @return string
942 */
943 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
944 // Set URL
945 switch ($action) {
946 case 'cancel':
947 $url = 'civicrm/contribute/unsubscribe';
948 break;
949
950 case 'billing':
951 //in notify mode don't return the update billing url
952 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
953 return NULL;
954 }
955 $url = 'civicrm/contribute/updatebilling';
956 break;
957
958 case 'update':
959 $url = 'civicrm/contribute/updaterecur';
960 break;
961 }
962
963 $session = CRM_Core_Session::singleton();
964 $userId = $session->get('userID');
965 $contactID = 0;
966 $checksumValue = '';
967 $entityArg = '';
968
969 // Find related Contact
970 if ($entityID) {
971 switch ($entity) {
972 case 'membership':
973 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
974 $entityArg = 'mid';
975 break;
976
977 case 'contribution':
978 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
979 $entityArg = 'coid';
980 break;
981
982 case 'recur':
983 $sql = "
984 SELECT con.contact_id
985 FROM civicrm_contribution_recur rec
986 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
987 WHERE rec.id = %1
988 GROUP BY rec.id";
989 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
990 $entityArg = 'crid';
991 break;
992 }
993 }
994
995 // Add entity arguments
996 if ($entityArg != '') {
997 // Add checksum argument
998 if ($contactID != 0 && $userId != $contactID) {
999 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
1000 }
1001 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
1002 }
1003
1004 // Else login URL
1005 if ($this->isSupported('accountLoginURL')) {
1006 return $this->accountLoginURL();
1007 }
1008
1009 // Else default
1010 return isset($this->_paymentProcessor['url_recur']) ? $this->_paymentProcessor['url_recur'] : '';
1011 }
1012
1013 }