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