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