CRM-15978 remove enotice introduced in last commit
[civicrm-core.git] / CRM / Core / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
30 /**
31 * Class CRM_Core_Payment.
32 *
33 * This class is the main class for the payment processor subsystem.
34 *
35 * It is the parent class for payment processors. It also holds some IPN related functions
36 * that need to be moved. In particular handlePaymentMethod should be moved to a factory class.
37 */
38 abstract class CRM_Core_Payment {
39
40 /**
41 * How are we getting billing information?
42 *
43 * FORM - we collect it on the same page
44 * BUTTON - the processor collects it and sends it back to us via some protocol
45 */
46 const
47 BILLING_MODE_FORM = 1,
48 BILLING_MODE_BUTTON = 2,
49 BILLING_MODE_NOTIFY = 4;
50
51 /**
52 * Which payment type(s) are we using?
53 *
54 * credit card
55 * direct debit
56 * or both
57 * @todo create option group - nb omnipay uses a 3rd type - transparent redirect cc
58 */
59 const
60 PAYMENT_TYPE_CREDIT_CARD = 1,
61 PAYMENT_TYPE_DIRECT_DEBIT = 2;
62
63 /**
64 * Subscription / Recurring payment Status
65 * START, END
66 */
67 const
68 RECURRING_PAYMENT_START = 'START',
69 RECURRING_PAYMENT_END = 'END';
70
71 protected $_paymentProcessor;
72
73 /**
74 * Singleton function used to manage this object.
75 *
76 * We will migrate to calling Civi\Payment\System::singleton()->getByProcessor($paymentProcessor)
77 * & Civi\Payment\System::singleton()->getById($paymentProcessor) directly as the main access methods & work
78 * to remove this function all together
79 *
80 * @param string $mode
81 * The mode of operation: live or test.
82 * @param array $paymentProcessor
83 * The details of the payment processor being invoked.
84 * @param object $paymentForm
85 * Deprecated - avoid referring to this if possible. If you have to use it document why as this is scary interaction.
86 * @param bool $force
87 * Should we force a reload of this payment object.
88 *
89 * @return CRM_Core_Payment
90 * @throws \CRM_Core_Exception
91 */
92 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
93 // make sure paymentProcessor is not empty
94 // CRM-7424
95 if (empty($paymentProcessor)) {
96 return CRM_Core_DAO::$_nullObject;
97 }
98 //we use two lines because we can't remove the '&singleton' without risking breakage
99 //of extension classes that extend this one
100 $object = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
101 return $object;
102 }
103
104 /**
105 * Log payment notification message to forensic system log.
106 *
107 * @todo move to factory class \Civi\Payment\System (or similar)
108 *
109 * @param array $params
110 *
111 * @return mixed
112 */
113 public static function logPaymentNotification($params) {
114 $message = 'payment_notification ';
115 if (!empty($params['processor_name'])) {
116 $message .= 'processor_name=' . $params['processor_name'];
117 }
118 if (!empty($params['processor_id'])) {
119 $message .= 'processor_id=' . $params['processor_id'];
120 }
121
122 $log = new CRM_Utils_SystemLogger();
123 $log->alert($message, $_REQUEST);
124 }
125
126 /**
127 * Check if capability is supported.
128 *
129 * Capabilities have a one to one relationship with capability-related functions on this class.
130 *
131 * Payment processor classes should over-ride the capability-specific function rather than this one.
132 *
133 * @param string $capability
134 * E.g BackOffice, LiveMode, FutureRecurStartDate.
135 *
136 * @return bool
137 */
138 public function supports($capability) {
139 $function = 'supports' . ucfirst($capability);
140 if (method_exists($this, $function)) {
141 return $this->$function();
142 }
143 return FALSE;
144 }
145
146 /**
147 * Are back office payments supported.
148 *
149 * e.g paypal standard won't permit you to enter a credit card associated
150 * with someone else's login.
151 * The intention is to support off-site (other than paypal) & direct debit but that is not all working yet so to
152 * reach a 'stable' point we disable.
153 *
154 * @return bool
155 */
156 protected function supportsBackOffice() {
157 if ($this->_paymentProcessor['billing_mode'] == 4 || $this->_paymentProcessor['payment_type'] != 1) {
158 return FALSE;
159 }
160 else {
161 return TRUE;
162 }
163 }
164
165 /**
166 * Are live payments supported - e.g dummy doesn't support this.
167 *
168 * @return bool
169 */
170 protected function supportsLiveMode() {
171 return TRUE;
172 }
173
174 /**
175 * Are test payments supported.
176 *
177 * @return bool
178 */
179 protected function supportsTestMode() {
180 return TRUE;
181 }
182
183 /**
184 * Should the first payment date be configurable when setting up back office recurring payments.
185 *
186 * We set this to false for historical consistency but in fact most new processors use tokens for recurring and can support this
187 *
188 * @return bool
189 */
190 protected function supportsFutureRecurStartDate() {
191 return FALSE;
192 }
193
194 /**
195 * Default payment instrument validation.
196 *
197 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
198 * Not a static function, because I need to check for payment_type.
199 *
200 * @param array $values
201 * @param array $errors
202 */
203 public function validatePaymentInstrument($values, &$errors) {
204 if ($this->_paymentProcessor['payment_type'] == 1) {
205 CRM_Core_Payment_Form::validateCreditCard($values, $errors);
206 }
207 }
208
209 /**
210 * Setter for the payment form that wants to use the processor.
211 *
212 * @deprecated
213 *
214 * @param CRM_Core_Form $paymentForm
215 */
216 public function setForm(&$paymentForm) {
217 $this->_paymentForm = $paymentForm;
218 }
219
220 /**
221 * Getter for payment form that is using the processor.
222 * @deprecated
223 * @return CRM_Core_Form
224 * A form object
225 */
226 public function getForm() {
227 return $this->_paymentForm;
228 }
229
230 /**
231 * Getter for accessing member vars.
232 * @todo believe this is unused
233 * @param string $name
234 *
235 * @return null
236 */
237 public function getVar($name) {
238 return isset($this->$name) ? $this->$name : NULL;
239 }
240
241 /**
242 * Get name for the payment information type.
243 * @todo - use option group + name field (like Omnipay does)
244 * @return string
245 */
246 public function getPaymentTypeName() {
247 return $this->_paymentProcessor['payment_type'] == 1 ? 'credit_card' : 'direct_debit';
248 }
249
250 /**
251 * Get label for the payment information type.
252 * @todo - use option group + labels (like Omnipay does)
253 * @return string
254 */
255 public function getPaymentTypeLabel() {
256 return $this->_paymentProcessor['payment_type'] == 1 ? 'Credit Card' : 'Direct Debit';
257 }
258
259 /**
260 * Get array of fields that should be displayed on the payment form.
261 * @todo make payment type an option value & use it in the function name - currently on debit & credit card work
262 * @return array
263 * @throws CiviCRM_API3_Exception
264 */
265 public function getPaymentFormFields() {
266 if ($this->_paymentProcessor['billing_mode'] == 4) {
267 return array();
268 }
269 return $this->_paymentProcessor['payment_type'] == 1 ? $this->getCreditCardFormFields() : $this->getDirectDebitFormFields();
270 }
271
272 /**
273 * Get array of fields that should be displayed on the payment form for credit cards.
274 *
275 * @return array
276 */
277 protected function getCreditCardFormFields() {
278 return array(
279 'credit_card_type',
280 'credit_card_number',
281 'cvv2',
282 'credit_card_exp_date',
283 );
284 }
285
286 /**
287 * Get array of fields that should be displayed on the payment form for direct debits.
288 *
289 * @return array
290 */
291 protected function getDirectDebitFormFields() {
292 return array(
293 'account_holder',
294 'bank_account_number',
295 'bank_identification_number',
296 'bank_name',
297 );
298 }
299
300 /**
301 * Return an array of all the details about the fields potentially required for payment fields.
302 *
303 * Only those determined by getPaymentFormFields will actually be assigned to the form
304 *
305 * @return array
306 * field metadata
307 */
308 public function getPaymentFormFieldsMetadata() {
309 //@todo convert credit card type into an option value
310 $creditCardType = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::creditCard();
311 return array(
312 'credit_card_number' => array(
313 'htmlType' => 'text',
314 'name' => 'credit_card_number',
315 'title' => ts('Card Number'),
316 'cc_field' => TRUE,
317 'attributes' => array(
318 'size' => 20,
319 'maxlength' => 20,
320 'autocomplete' => 'off',
321 ),
322 'is_required' => TRUE,
323 ),
324 'cvv2' => array(
325 'htmlType' => 'text',
326 'name' => 'cvv2',
327 'title' => ts('Security Code'),
328 'cc_field' => TRUE,
329 'attributes' => array(
330 'size' => 5,
331 'maxlength' => 10,
332 'autocomplete' => 'off',
333 ),
334 'is_required' => CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
335 'cvv_backoffice_required',
336 NULL,
337 1
338 ),
339 'rules' => array(
340 array(
341 '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.'),
342 'rule_name' => 'integer',
343 'rule_parameters' => NULL,
344 ),
345 ),
346 ),
347 'credit_card_exp_date' => array(
348 'htmlType' => 'date',
349 'name' => 'credit_card_exp_date',
350 'title' => ts('Expiration Date'),
351 'cc_field' => TRUE,
352 'attributes' => CRM_Core_SelectValues::date('creditCard'),
353 'is_required' => TRUE,
354 'rules' => array(
355 array(
356 'rule_message' => ts('Card expiration date cannot be a past date.'),
357 'rule_name' => 'currentDate',
358 'rule_parameters' => TRUE,
359 ),
360 ),
361 ),
362 'credit_card_type' => array(
363 'htmlType' => 'select',
364 'name' => 'credit_card_type',
365 'title' => ts('Card Type'),
366 'cc_field' => TRUE,
367 'attributes' => $creditCardType,
368 'is_required' => FALSE,
369 ),
370 'account_holder' => array(
371 'htmlType' => 'text',
372 'name' => 'account_holder',
373 'title' => ts('Account Holder'),
374 'cc_field' => TRUE,
375 'attributes' => array(
376 'size' => 20,
377 'maxlength' => 34,
378 'autocomplete' => 'on',
379 ),
380 'is_required' => TRUE,
381 ),
382 //e.g. IBAN can have maxlength of 34 digits
383 'bank_account_number' => array(
384 'htmlType' => 'text',
385 'name' => 'bank_account_number',
386 'title' => ts('Bank Account Number'),
387 'cc_field' => TRUE,
388 'attributes' => array(
389 'size' => 20,
390 'maxlength' => 34,
391 'autocomplete' => 'off',
392 ),
393 'rules' => array(
394 array(
395 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
396 'rule_name' => 'nopunctuation',
397 'rule_parameters' => NULL,
398 ),
399 ),
400 'is_required' => TRUE,
401 ),
402 //e.g. SWIFT-BIC can have maxlength of 11 digits
403 'bank_identification_number' => array(
404 'htmlType' => 'text',
405 'name' => 'bank_identification_number',
406 'title' => ts('Bank Identification Number'),
407 'cc_field' => TRUE,
408 'attributes' => array(
409 'size' => 20,
410 'maxlength' => 11,
411 'autocomplete' => 'off',
412 ),
413 'is_required' => TRUE,
414 'rules' => array(
415 array(
416 'rule_message' => ts('Please enter a valid Bank Identification Number (value must not contain punctuation characters).'),
417 'rule_name' => 'nopunctuation',
418 'rule_parameters' => NULL,
419 ),
420 ),
421 ),
422 'bank_name' => array(
423 'htmlType' => 'text',
424 'name' => 'bank_name',
425 'title' => ts('Bank Name'),
426 'cc_field' => TRUE,
427 'attributes' => array(
428 'size' => 20,
429 'maxlength' => 64,
430 'autocomplete' => 'off',
431 ),
432 'is_required' => TRUE,
433
434 ),
435 );
436 }
437
438 /**
439 * Calling this from outside the payment subsystem is deprecated - use doPayment.
440 *
441 * Does a server to server payment transaction.
442 *
443 * Note that doPayment will throw an exception so the code may need to be modified
444 *
445 * @param array $params
446 * Assoc array of input parameters for this transaction.
447 *
448 * @return array
449 * the result in an nice formatted array (or an error object)
450 * @abstract
451 */
452 abstract protected function doDirectPayment(&$params);
453
454 /**
455 * Process payment - this function wraps around both doTransferPayment and doDirectPayment
456 * it ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms more agnostic
457 *
458 * @param array $params
459 *
460 * @param $component
461 *
462 * @return array
463 * (modified)
464 * @throws CRM_Core_Exception
465 */
466 public function doPayment(&$params, $component = 'contribute') {
467 if ($this->_paymentProcessor['billing_mode'] == 4) {
468 $result = $this->doTransferCheckout($params, $component);
469 }
470 else {
471 $result = $this->doDirectPayment($params, $component);
472 }
473 if (is_a($result, 'CRM_Core_Error')) {
474 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
475 }
476 //CRM-15767 - Submit Credit Card Contribution not being saved
477 return $result;
478 }
479
480 /**
481 * This function checks to see if we have the right config values.
482 *
483 * @return string
484 * the error message if any
485 */
486 abstract protected function checkConfig();
487
488 /**
489 * @param $paymentProcessor
490 * @todo move to paypal class or remover
491 * @return bool
492 */
493 public static function paypalRedirect(&$paymentProcessor) {
494 if (!$paymentProcessor) {
495 return FALSE;
496 }
497
498 if (isset($_GET['payment_date']) &&
499 isset($_GET['merchant_return_link']) &&
500 CRM_Utils_Array::value('payment_status', $_GET) == 'Completed' &&
501 $paymentProcessor['payment_processor_type'] == "PayPal_Standard"
502 ) {
503 return TRUE;
504 }
505
506 return FALSE;
507 }
508
509 /**
510 * @todo move to0 \Civi\Payment\System factory method
511 * Page callback for civicrm/payment/ipn
512 */
513 public static function handleIPN() {
514 self::handlePaymentMethod(
515 'PaymentNotification',
516 array(
517 'processor_name' => @$_GET['processor_name'],
518 'processor_id' => @$_GET['processor_id'],
519 'mode' => @$_GET['mode'],
520 )
521 );
522 CRM_Utils_System::civiExit();
523 }
524
525 /**
526 * Payment callback handler.
527 *
528 * The processor_name or processor_id is passed in.
529 * Note that processor_id is more reliable as one site may have more than one instance of a
530 * processor & ideally the processor will be validating the results
531 * Load requested payment processor and call that processor's handle<$method> method
532 *
533 * @todo move to \Civi\Payment\System factory method
534 *
535 * @param string $method
536 * 'PaymentNotification' or 'PaymentCron'
537 * @param array $params
538 */
539 public static function handlePaymentMethod($method, $params = array()) {
540 if (!isset($params['processor_id']) && !isset($params['processor_name'])) {
541 CRM_Core_Error::fatal("Either 'processor_id' or 'processor_name' param is required for payment callback");
542 }
543 self::logPaymentNotification($params);
544
545 $sql = "SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id
546 FROM civicrm_payment_processor_type ppt
547 INNER JOIN civicrm_payment_processor pp
548 ON pp.payment_processor_type_id = ppt.id
549 AND pp.is_active";
550
551 if (isset($params['processor_id'])) {
552 $sql .= " WHERE pp.id = %2";
553 $args[2] = array($params['processor_id'], 'Integer');
554 $notFound = "No active instances of payment processor ID#'{$params['processor_id']}' were found.";
555 }
556 else {
557 // This is called when processor_name is passed - passing processor_id instead is recommended.
558 $sql .= " WHERE ppt.name = %2 AND pp.is_test = %1";
559 $args[1] = array((CRM_Utils_Array::value('mode', $params) == 'test') ? 1 : 0, 'Integer');
560 $args[2] = array($params['processor_name'], 'String');
561 $notFound = "No active instances of the '{$params['processor_name']}' payment processor were found.";
562 }
563
564 $dao = CRM_Core_DAO::executeQuery($sql, $args);
565
566 // Check whether we found anything at all.
567 if (!$dao->N) {
568 CRM_Core_Error::fatal($notFound);
569 }
570
571 $method = 'handle' . $method;
572 $extension_instance_found = FALSE;
573
574 // In all likelihood, we'll just end up with the one instance returned here. But it's
575 // possible we may get more. Hence, iterate through all instances ..
576
577 while ($dao->fetch()) {
578 // Check pp is extension
579 $ext = CRM_Extension_System::singleton()->getMapper();
580 if ($ext->isExtensionKey($dao->class_name)) {
581 $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
582 require_once $ext->classToPath($paymentClass);
583 }
584 else {
585 // Legacy or extension as module instance
586 if (empty($paymentClass)) {
587 $paymentClass = 'CRM_Core_' . $dao->class_name;
588
589 }
590 }
591
592 $processorInstance = $processorInstance = Civi\Payment\System::singleton()->getById($dao->processor_id);
593
594 // Should never be empty - we already established this processor_id exists and is active.
595 if (empty($processorInstance)) {
596 continue;
597 }
598
599 // Does PP implement this method, and can we call it?
600 if (!method_exists($processorInstance, $method) ||
601 !is_callable(array($processorInstance, $method))
602 ) {
603 // on the off chance there is a double implementation of this processor we should keep looking for another
604 // note that passing processor_id is more reliable & we should work to deprecate processor_name
605 continue;
606 }
607
608 // Everything, it seems, is ok - execute pp callback handler
609 $processorInstance->$method();
610 $extension_instance_found = TRUE;
611 }
612
613 if (!$extension_instance_found) {
614 CRM_Core_Error::fatal(
615 "No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" .
616 "$method method is unsupported in legacy payment processors."
617 );
618 }
619 }
620
621 /**
622 * Check whether a method is present ( & supported ) by the payment processor object.
623 *
624 * @param string $method
625 * Method to check for.
626 *
627 * @return bool
628 */
629 public function isSupported($method = 'cancelSubscription') {
630 return method_exists(CRM_Utils_System::getClassName($this), $method);
631 }
632
633 /**
634 * Get url for users to manage this recurring contribution for this processor.
635 *
636 * @param int $entityID
637 * @param null $entity
638 * @param string $action
639 *
640 * @return string
641 */
642 public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') {
643 // Set URL
644 switch ($action) {
645 case 'cancel':
646 $url = 'civicrm/contribute/unsubscribe';
647 break;
648
649 case 'billing':
650 //in notify mode don't return the update billing url
651 if (!$this->isSupported('updateSubscriptionBillingInfo')) {
652 return NULL;
653 }
654 $url = 'civicrm/contribute/updatebilling';
655 break;
656
657 case 'update':
658 $url = 'civicrm/contribute/updaterecur';
659 break;
660 }
661
662 $session = CRM_Core_Session::singleton();
663 $userId = $session->get('userID');
664 $contactID = 0;
665 $checksumValue = '';
666 $entityArg = '';
667
668 // Find related Contact
669 if ($entityID) {
670 switch ($entity) {
671 case 'membership':
672 $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
673 $entityArg = 'mid';
674 break;
675
676 case 'contribution':
677 $contactID = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $entityID, "contact_id");
678 $entityArg = 'coid';
679 break;
680
681 case 'recur':
682 $sql = "
683 SELECT con.contact_id
684 FROM civicrm_contribution_recur rec
685 INNER JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
686 WHERE rec.id = %1
687 GROUP BY rec.id";
688 $contactID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($entityID, 'Integer')));
689 $entityArg = 'crid';
690 break;
691 }
692 }
693
694 // Add entity arguments
695 if ($entityArg != '') {
696 // Add checksum argument
697 if ($contactID != 0 && $userId != $contactID) {
698 $checksumValue = '&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf');
699 }
700 return CRM_Utils_System::url($url, "reset=1&{$entityArg}={$entityID}{$checksumValue}", TRUE, NULL, FALSE, TRUE);
701 }
702
703 // Else login URL
704 if ($this->isSupported('accountLoginURL')) {
705 return $this->accountLoginURL();
706 }
707
708 // Else default
709 return $this->_paymentProcessor['url_recur'];
710 }
711
712 }