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