Merge pull request #18019 from eileenmcnaughton/event_clean
[civicrm-core.git] / CRM / Core / Payment / Realex.php
index 610b101cbdb6e251f8c353bbced38b378c7e1ba1..6fa22c9ccd867c3dcaebe88fb6aa1c36f7248fc4 100644 (file)
@@ -1,29 +1,14 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 5                                                  |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM.                                    |
- |                                                                    |
- | CiviCRM is free software; you can copy, modify, and distribute it  |
- | under the terms of the GNU Affero General Public License           |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
- |                                                                    |
- | CiviCRM is distributed in the hope that it will be useful, but     |
- | WITHOUT ANY WARRANTY; without even the implied warranty of         |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
- | See the GNU Affero General Public License for more details.        |
+ | Copyright CiviCRM LLC. All rights reserved.                        |
  |                                                                    |
- | You should have received a copy of the GNU Affero General Public   |
- | License and the CiviCRM Licensing Exception along                  |
- | with this program; if not, contact CiviCRM LLC                     |
- | at info[AT]civicrm[DOT]org. If you have questions about the        |
- | GNU Affero General Public License or the licensing of CiviCRM,     |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ | This work is published under the GNU AGPLv3 license with some      |
+ | permitted exceptions and without any warranty. For full license    |
+ | and copyright information, see https://civicrm.org/licensing       |
  +--------------------------------------------------------------------+
  */
 
-
 /*
  * Copyright (C) 2009
  * Licensed to CiviCRM under the Academic Free License version 3.0.
  * Written and contributed by Kirkdesigns (http://www.kirkdesigns.co.uk)
  */
 
+use Civi\Payment\Exception\PaymentProcessorException;
+
 /**
  *
  * @package CRM
  * @author Tom Kirkpatrick <tkp@kirkdesigns.co.uk>
- * $Id$
  */
 class CRM_Core_Payment_Realex extends CRM_Core_Payment {
   const AUTH_APPROVED = '00';
 
-  protected $_mode = NULL;
+  protected $_mode;
 
   protected $_params = [];
 
@@ -50,9 +36,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
    * @param string $mode
    *   The mode of operation: live or test.
    *
-   * @param $paymentProcessor
-   *
-   * @return \CRM_Core_Payment_Realex
+   * @param array $paymentProcessor
    */
   public function __construct($mode, &$paymentProcessor) {
     $this->_mode = $mode;
@@ -75,24 +59,22 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
    *
    * @return array
    *   the result in a nice formatted array (or an error object)
+   *
+   * @throws \Civi\Payment\Exception\PaymentProcessorException
    */
   public function doDirectPayment(&$params) {
 
     if (!defined('CURLOPT_SSLCERT')) {
-      return self::error(9001, ts('RealAuth requires curl with SSL support'));
+      throw new PaymentProcessorException(ts('RealAuth requires curl with SSL support'), 9001);
     }
 
     $result = $this->setRealexFields($params);
 
-    if ($result !== TRUE) {
-      return $result;
-    }
-
     /**********************************************************
      * Check to see if we have a duplicate before we send
      **********************************************************/
     if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array::value('contributionID', $params))) {
-      return self::error(9004, ts('It appears that this transaction is a duplicate.  Have you already submitted the form once?  If so there may have been a connection problem.  Check your email for a receipt from Authorize.net.  If you do not receive a receipt within 2 hours you can try your transaction again.  If you continue to have problems please contact the site administrator.'));
+      throw new PaymentProcessorException(ts('It appears that this transaction is a duplicate.  Have you already submitted the form once?  If so there may have been a connection problem.  Check your email for a receipt from Authorize.net.  If you do not receive a receipt within 2 hours you can try your transaction again.  If you continue to have problems please contact the site administrator.'), 9004);
     }
 
     // Create sha1 hash for request
@@ -135,7 +117,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     $submit = curl_init($this->_paymentProcessor['url_site']);
 
     if (!$submit) {
-      return self::error(9002, ts('Could not initiate connection to payment gateway'));
+      throw new PaymentProcessorException(ts('Could not initiate connection to payment gateway'), 9002);
     }
 
     curl_setopt($submit, CURLOPT_HTTPHEADER, ['SOAPAction: ""']);
@@ -155,7 +137,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     $response_xml = curl_exec($submit);
 
     if (!$response_xml) {
-      return self::error(curl_errno($submit), curl_error($submit));
+      throw new PaymentProcessorException(curl_error($submit), curl_errno($submit));
     }
 
     curl_close($submit);
@@ -167,7 +149,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     // Parse the response xml
     $xml_parser = xml_parser_create();
     if (!xml_parse($xml_parser, $response_xml)) {
-      return self::error(9003, 'XML Error');
+      throw new PaymentProcessorException('XML Error', 9003);
     }
 
     $response = $this->xml_parse_into_assoc($response_xml);
@@ -178,19 +160,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
 
     // Return an error if authentication was not successful
     if ($response['RESULT'] !== self::AUTH_APPROVED) {
-      return self::error($response['RESULT'], ' ' . $response['MESSAGE']);
-    }
-
-    // Check the response hash
-    $hashme = "{$this->_getParam('timestamp')}.{$this->_getParam('merchant_ref')}.{$this->_getParam('order_id')}.{$response['RESULT']}.{$response['MESSAGE']}.{$response['PASREF']}.{$response['AUTHCODE']}";
-    $sha1hash = sha1($hashme);
-    $hashme = "$sha1hash.{$this->_getParam('secret')}";
-    $sha1hash = sha1($hashme);
-
-    if ($response['SHA1HASH'] != $sha1hash) {
-      // FIXME: Need to actually check this - I couldn't get the
-      // hashes to match so I'm commenting out for now'
-      // return self::error( 9001, "Hash error, please report this to the webmaster" );
+      throw new PaymentProcessorException($this->getDisplayError($response['RESULT'], ' ' . $response['MESSAGE']));
     }
 
     // FIXME: We are using the trxn_result_code column to store all these extra details since there
@@ -253,7 +223,8 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
   }
 
   /**
-   * Private helper for  xml_parse_into_assoc, to recusively parsing the result
+   * Private helper for  xml_parse_into_assoc, to recursively parsing the result.
+   *
    * @param $input
    * @param int $depth
    *
@@ -293,11 +264,11 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
    *
    * @param array $params
    *
-   * @return bool
+   * @throws \Civi\Payment\Exception\PaymentProcessorException
    */
   public function setRealexFields(&$params) {
     if ((int) $params['amount'] <= 0) {
-      return self::error(9001, ts('Amount must be positive'));
+      throw new PaymentProcessorException(ts('Amount must be positive'), 9001);
     }
 
     // format amount to be in smallest possible units
@@ -334,7 +305,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
         break;
 
       default:
-        return self::error(9001, ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type']);
+        throw new PaymentProcessorException(ts('Credit card type not supported by Realex:') . ' ' . $params['credit_card_type'], 9001);
     }
 
     // get the card holder name - cater cor customized billing forms
@@ -360,11 +331,9 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     $this->_setParam('varref', $params['contributionType_name']);
     $comment = $params['description'] . ' (page id:' . $params['contributionPageID'] . ')';
     $this->_setParam('comments', $comment);
-    //$this->_setParam('currency',      $params['currencyID']);
 
     // set the currency to the default which can be overrided.
-    $config = CRM_Core_Config::singleton();
-    $this->_setParam('currency', $config->defaultCurrency);
+    $this->_setParam('currency', CRM_Core_Config::singleton()->defaultCurrency);
 
     // Format the expiry date to MMYY
     $expmonth = (string) $params['month'];
@@ -382,10 +351,8 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     }
 
     // Create timestamp
-    $timestamp = strftime("%Y%m%d%H%M%S");
+    $timestamp = strftime('%Y%m%d%H%M%S');
     $this->_setParam('timestamp', $timestamp);
-
-    return TRUE;
   }
 
   /**
@@ -402,9 +369,7 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     if (isset($this->_params[$field])) {
       return $this->_params[$field];
     }
-    else {
-      return '';
-    }
+    return '';
   }
 
   /**
@@ -413,50 +378,12 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
    *
    * @param string $field
    * @param mixed $value
-   *
-   * @return bool
-   *   false if value is not a scalar, true if successful
    */
   public function _setParam($field, $value) {
     if (!is_scalar($value)) {
-      return FALSE;
-    }
-    else {
-      $this->_params[$field] = $value;
-    }
-  }
-
-  /**
-   * @param null $errorCode
-   * @param null $errorMessage
-   *
-   * @return object
-   */
-  public function &error($errorCode = NULL, $errorMessage = NULL) {
-    $e = CRM_Core_Error::singleton();
-
-    if ($errorCode) {
-      if ($errorCode == '101' || $errorCode == '102') {
-        $display_error = ts('Card declined by bank. Please try with a different card.');
-      }
-      elseif ($errorCode == '103') {
-        $display_error = ts('Card reported lost or stolen. This incident will be reported.');
-      }
-      elseif ($errorCode == '501') {
-        $display_error = ts("It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. Check your email for a receipt for this transaction.  If you do not receive a receipt within 2 hours you can try your transaction again.  If you continue to have problems please contact the site administrator.");
-      }
-      elseif ($errorCode == '509') {
-        $display_error = $errorMessage;
-      }
-      else {
-        $display_error = ts('We were unable to process your payment at this time. Please try again later.');
-      }
-      $e->push($errorCode, 0, NULL, $display_error);
-    }
-    else {
-      $e->push(9001, 0, NULL, ts('We were unable to process your payment at this time. Please try again later.'));
+      return;
     }
-    return $e;
+    $this->_params[$field] = $value;
   }
 
   /**
@@ -478,9 +405,34 @@ class CRM_Core_Payment_Realex extends CRM_Core_Payment {
     if (!empty($error)) {
       return implode('<p>', $error);
     }
+    return NULL;
+  }
+
+  /**
+   * Get the error to display.
+   *
+   * @param string $errorCode
+   * @param string $errorMessage
+   *
+   * @return string
+   */
+  protected function getDisplayError($errorCode, $errorMessage): string {
+    if ($errorCode === '101' || $errorCode === '102') {
+      $display_error = ts('Card declined by bank. Please try with a different card.');
+    }
+    elseif ($errorCode === '103') {
+      $display_error = ts('Card reported lost or stolen. This incident will be reported.');
+    }
+    elseif ($errorCode === '501') {
+      $display_error = ts('It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. Check your email for a receipt for this transaction.  If you do not receive a receipt within 2 hours you can try your transaction again.  If you continue to have problems please contact the site administrator.');
+    }
+    elseif ($errorCode === '509') {
+      $display_error = $errorMessage;
+    }
     else {
-      return NULL;
+      $display_error = ts('We were unable to process your payment at this time. Please try again later.');
     }
+    return $display_error;
   }
 
 }