<?php
require_once 'modules/admin/models/GatewayPlugin.php';
require_once 'newedge/classes/XmlFunctions.php';

class PluginQuantum extends GatewayPlugin
{
    function getVariables()
    {
        $variables = array (
            /*T*/'Plugin Name'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'How CE sees this plugin (not to be confused with the Signup Name)'/*/T*/,
                                'value'         =>/*T*/'Quantum Gateway'/*/T*/
                               ),
            /*T*/'In Signup'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES if you want to include this payment processor in the signup script.'/*/T*/,
                                'value'         =>'0'
                               ),
            /*T*/"One-Time Payments"/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES if you want to allow customers to make one-time payments through this payment processor.'/*/T*/,
                                'value'         =>0
                               ),
            /*T*/'Use Verify By Visa and MasterCard SecureCode'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Be sure to have these services enabled in your gateway before attempting to use them.'/*/T*/,
                                'value'         =>0,
                               ),
            /*T*/'Use DialVerify Service'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Be sure to have this service enabled in your gateway before attempting to use it.'/*/T*/,
                                'value'         =>0,
                               ),
            /*T*/'Use Maxmind'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Use Quantum Gateway\'s Maxmind fraud screening services.'/*/T*/,
                                'value'         =>0,
                               ),
            /*T*/'Quantum Gateway Username'/*/T*/ => array (
                                'type'          =>'text',
                                'description'   =>/*T*/'Please enter your Quantum Gateway Username Here.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Quantum Gateway RestrictKey'/*/T*/ => array (
                                'type'          =>'password',
                                'description'   =>/*T*/'Please enter your Quantum Gateway RestrictKey Here.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Accept CC Number'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'Selecting YES allows the entering of CC numbers when using this plugin type. No will prevent entering of cc information'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'Visa'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES to allow Visa card acceptance with this plugin.  No will prevent this card type.'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'MasterCard'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES to allow MasterCard acceptance with this plugin. No will prevent this card type.'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'AmericanExpress'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES to allow American Express card acceptance with this plugin. No will prevent this card type.'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'Discover'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES to allow Discover card acceptance with this plugin. No will prevent this card type.'/*/T*/,
                                'value'         =>'0'
                               ),
            /*T*/'Invoice After Signup'/*/T*/ => array (
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select YES if you want an invoice sent to the customer after signup is complete.'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'Signup Name'/*/T*/ => array (
                                'type'          =>'text',
                                'description'   =>/*T*/'Select the name to display in the signup process for this payment type. Example: eCheck or Credit Card.'/*/T*/,
                                'value'         =>'Credit Card'
                               ),
            /*T*/'Payment Form Title'/*/T*/ => array(
                                'type'          =>'text',
                                'description'   =>/*T*/'The Payment Form will only be displayed when extra user input is required, i.e. when using Verified By Visa, MaterCard SecureCode or DialVerify.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Payment Form Header'/*/T*/ => array(
                                'type'          =>'textarea',
                                'description'   =>/*T*/'The Payment Form will only be displayed when extra user input is required, i.e. when using Verified By Visa, MaterCard SecureCode or DialVerify. HTML is accepted.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Receipt Page Header'/*/T*/ => array(
                                'type'          =>'textarea',
                                'description'   =>/*T*/'The Receipt Page will only be displayed when extra user input is required, i.e. when using Verified By Visa, MaterCard SecureCode or DialVerify. HTML is accepted.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Receipt Page Footer'/*/T*/ => array(
                                'type'          =>'textarea',
                                'description'   =>/*T*/'The Receipt Footer will only be displayed when extra user input is required, i.e. when using Verified By Visa, MaterCard SecureCode or DialVerify. HTML is accepted.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Dummy Plugin'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'1 = Only used to specify a billing type for a customer. 0 = full fledged plugin requiring complete functions'/*/T*/,
                                'value'         =>'0'
                               ),
            /*T*/'Auto Payment'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'No description'/*/T*/,
                                'value'         =>'1'
                               ),
            /*T*/'30 Day Billing'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'Select YES if you want ClientExec to treat monthly billing by 30 day intervals.  If you select NO then the same day will be used to determine intervals.'/*/T*/,
                                'value'         =>'0'
                               ),
           /*T*/"Check CVV2"/*/T*/ => array (
                                "type"          =>"yesno",
                                "description"   =>/*T*/"Select YES if you want to accept CVV2 for this plugin."/*/T*/,
                                "value"         =>"0"
                               )
        );
    
        return $variables;
    }
    
    function singlepayment($params)
    {
        require_once 'newedge/classes/NE_Network.php';

        // VbV/MCSC and Dialverify (only used in signup) require some interaction from the user with the provider server, 
        // so if those aren't set up then use autopayment which is silent.
        if (!$params['isSignup'] || (!$params['plugin_quantum_Use Verify By Visa and MasterCard SecureCode'] && !$params['plugin_quantum_Use DialVerify Service'])) {
            return $this->autopayment($params);
        }
    
        $params = NE_Lib::_array_map_recursive(array('NE_Lib', 'escapeHTMLAttributeValue'), $params);
    
        $callbackURL = mb_substr($params['clientExecURL'],-1,1) == '//' ? $params['clientExecURL']."plugins/gateways/quantum/callback.php" : $params['clientExecURL']."/plugins/gateways/quantum/callback.php";
        $CCMo = mb_substr($params['userCCExp'], 0, 2);
        $CCYear = mb_substr($params['userCCExp'], 3);
        $useMaxmind = $params['plugin_quantum_Use Maxmind']? 1 : 2;
    
        $html = "<html>\n<head>\n</head>\n<body>\n"
               ."<form name=\"frmQuantumGateway\" action=\"https://secure.quantumgateway.com/cgi/clientexec.php\" method=\"post\">\n"
               ."<input type=\"hidden\" name=\"gwlogin\" value=\"{$params['plugin_quantum_Quantum Gateway Username']}\">\n"
               ."<input type=\"hidden\" name=\"RestrictKey\" value=\"{$params['plugin_quantum_Quantum Gateway RestrictKey']}\">\n"
               ."<input type=\"hidden\" name=\"post_return_url\" value=\"$callbackURL\">\n"
               ."<input type=\"hidden\" name=\"ResponseMethod\" value=\"GET\" />\n"
               ."<input type=\"hidden\" name=\"ID\" value=\"{$params['userID']}\">\n"
               ."<input type=\"hidden\" name=\"customer_ip\" value=\"".NE_Network::getRemoteAddr()."\">\n"
               ."<input type=\"hidden\" name=\"amount\" value=\"{$params['invoiceTotal']}\">\n"
               ."<input type=\"hidden\" name=\"FNAME\" value=\"{$params['userFirstName']}\">\n"
               ."<input type=\"hidden\" name=\"LNAME\" value=\"{$params['userLastName']}\">\n"
               ."<input type=\"hidden\" name=\"BADDR1\" value=\"{$params['userAddress']}\">\n"
               ."<input type=\"hidden\" name=\"BZIP1\" value=\"{$params['userZipcode']}\">\n"
               ."<input type=\"hidden\" name=\"BCITY\" value=\"{$params['userCity']}\">\n"
               ."<input type=\"hidden\" name=\"BCUST_EMAIL\" value=\"{$params['userEmail']}\">\n"
               ."<input type=\"hidden\" name=\"BSTATE\" value=\"{$params['userState']}\">\n"
               ."<input type=\"hidden\" name=\"BCOUNTRY\" value=\"{$params['userCountry']}\">\n"
               ."<input type=\"hidden\" name=\"phone\" value=\"{$params['userPhone']}\">\n"
               ."<input type=\"hidden\" name=\"trans_method\" value=\"CC\">\n"
               ."<input type=\"hidden\" name=\"ccnum\" value=\"{$params['userCCNumber']}\">\n";
        
        // TAKEN FROM: http://www.quantumgateway.com/view_developer.php?Cat1=2
        if($params['userCCCVV2'] != ''){
            // CVV - CVV2
            //     Security code on the back or front of the credit card
            $html .= "<input type=\"hidden\" name=\"CVV2\" value=\"{$params['userCCCVV2']}\">\n";
            
            // Type Of CVV2 being sent - CVVtype
            //     0 - Not Passing CVV2
            //     1 - CVV2 is being passed
            //     2 - CVV2 on card is unreadable
            //     9 - Card does not have CVV2 imprint
            $html .= "<input type=\"hidden\" name=\"CVVtype\" value=\"1\">\n";
        }
        
        $html .= "<input type=\"hidden\" name=\"ccmo\" value=\"$CCMo\">\n"
                ."<input type=\"hidden\" name=\"ccyr\" value=\"$CCYear\">\n"
                ."<input type=\"hidden\" name=\"invoice_num\" value=\"{$params['invoiceNumber']}\">\n"
                ."<input type=\"hidden\" name=\"invoice_description\" value=\"{$params['invoiceDescription']}\">\n"
                ."<input type=\"hidden\" name=\"MAXMIND\" value=\"$useMaxmind\">\n"
                ."<input type=\"hidden\" name=\"page_heading\" value=\"{$params['plugin_quantum_Payment Form Title']}\">\n"
                ."<input type=\"hidden\" name=\"payment_heading\" value=\"{$params['plugin_quantum_Payment Form Header']}\">\n"
                ."<input type=\"hidden\" name=\"header_receipt\" value=\"{$params['plugin_quantum_Receipt Page Header']}\">\n"
                ."<input type=\"hidden\" name=\"footer_receipt\" value=\"{$params['plugin_quantum_Receipt Page Footer']}\">\n"
                ."<script language=\"JavaScript\">\n"
                ."   document.forms['frmQuantumGateway'].submit();\n"
                ."</script>\n"
                ."</form>\n</body>\n</html>\n";
        
        echo $html;
        exit;
    }
    
    function autopayment($params)
    {
        require_once 'modules/billing/models/class.gateway.plugin.php';
        require_once 'newedge/classes/NE_Network.php';
    
        $requestArr = array(
            'gwlogin'               => $params['plugin_quantum_Quantum Gateway Username'],
            'trans_method'          => 'CC',
            'cust_id'               => $params['userID'],
            'customer_ip'           => NE_Network::getRemoteAddr(),
            'invoice_num'           => $params['invoiceNumber'],
            'invoice_description'   => $params['invoiceDescription'],
            'ccnum'                 => $params['userCCNumber'],
            'ccmo'                  => mb_substr($params['userCCExp'], 0, 2),
            'ccyr'                  => mb_substr($params['userCCExp'], 3),
            'amount'                => $params['invoiceTotal'],
            'BADDR1'                => $params['userAddress'],
            'BCITY'                 => $params['userCity'],
            'BSTATE'                => $params['userState'],
            'BCOUNTRY'              => $params['userCountry'],
            'BZIP1'                 => $params['userZipcode'],
            'BCUST_EMAIL'           => $params['userEmail'],
            'phone'                 => $params['userPhone'],
            'RestrictKey'           => $params['plugin_quantum_Quantum Gateway RestrictKey'],
            'FNAME'                 => $params['userFirstName'],
            'LNAME'                 => $params['userLastName'],
            'MAXMIND'               => ($params['plugin_quantum_Use Maxmind'] && $params['isSignup'])? 1 : 2,
            'post_return_url'       => mb_substr($params['clientExecURL'],-1,1) == '//' ? $params['clientExecURL']."plugins/gateways/quantum/callback.php" : $params['clientExecURL']."/plugins/gateways/quantum/callback.php",
            'ResponseMethod'        => 'GET',   // not sure this is needed here, but just in case...
        );

        $cPlugin = new Plugin($params['invoiceNumber'], "", $this->user);

        if (isset($params['refund']) && $params['refund']) {
            $isRefund = true;
            $cPlugin->setAction('refund');
            $requestArr['trans_type'] = 'RETURN';
        } else {
            $isRefund = false;
            $cPlugin->setAction('charge');
        }

        $request = '';
        $firstIteration = true;
        foreach ($requestArr as $var => $value) {
            if (!$firstIteration) {
                $request .= '&';
            }
            $request .= "$var=".urlencode($value);
            $firstIteration = false;
        }
    
        $response = NE_Network::curlRequest($this->settings, 'https://secure.quantumgateway.com/cgi/clientexecT.php', $request, false, true);

        // response is a "|"-separated string for payments, and just a string for refunds...
        if (!$isRefund) {
            $response = explode("|", trim($response));
            $transactionID = mb_substr($response[2], 1, -1);
        } else {
            $transactionID = $params['invoiceRefundTransactionId'];
        }
    
        $cPlugin->setAmount($params['invoiceTotal']);
        $cPlugin->setTransactionID($transactionID);
    
        if (!$isRefund && $response[0] != '"APPROVED"') {
            $cPlugin->setAction('charge');
            $cPlugin->PaymentRejected("Quantum Gateway payment of {$params['invoiceTotal']} was rejected.");
            return 'Payment rejected by credit card gateway provider';
        }

        if ($isRefund && strpos($response, 'APPROVED') === false) {
            $cPlugin->setAction('refund');
            $cPlugin->PaymentRejected("Quantum Gateway refund of {$params['invoiceTotal']} was rejected.");
            return 'Refund rejected by credit card gateway provider';
        }
    
        if ($isRefund) {
            $cPlugin->setAction('refund');
            $cPlugin->PaymentAccepted($params['invoiceTotal'], "Quantum Gateway refund of {$params['invoiceTotal']} was successfully processed.", $transactionID);
            return array('AMOUNT' => $params['invoiceTotal']);
        } else {
            $cPlugin->setAction('charge');
            $cPlugin->PaymentAccepted($params['invoiceTotal'], "Quantum Gateway payment of {$params['invoiceTotal']} was accepted.", $transactionID);
            return '';
        }
    }
    
    function credit($params)
    {
        $params['refund'] = true;
        return $this->autopayment($params);
    }
    
    function ShowTransactionDetails($params){
        $GatewayKey = $params['plugin_quantum_Quantum Gateway RestrictKey'];
        
        $RequestType = "ShowTransactionDetails";
        $paramsArray = array(
                                "TransactionID"   => $params['TransactionID'],
                            );
        
        return $this->XMLrequest($params, $GatewayKey, $RequestType, $paramsArray);
    }
    
    function XMLrequest($params, $GatewayKey, $RequestType, $paramsArray){
        $url = "https://secure.quantumgateway.com/cgi/xml_requester.php";
        
        $xml  = "<QGWRequest>\n";
        $xml .= "    <Authentication>\n";
        $xml .= "        <GatewayLogin>".$params['plugin_quantum_Quantum Gateway Username']."</GatewayLogin>\n";
        $xml .= "        <GatewayKey>".$GatewayKey."</GatewayKey>\n";
        $xml .= "    </Authentication>\n";
        $xml .= "    <Request>\n";
        $xml .= "        <RequestType>".$RequestType."</RequestType>\n";
        foreach($paramsArray AS $paramName => $paramValue){
            $xml .= "        <".$paramName;
            if($paramValue != ''){
                $xml .= ">".$paramValue."</".$paramName.">\n";
            }else{
                $xml .= "/>\n";
            }
        }
        $xml .= "    </Request>\n";
        $xml .= "</QGWRequest>\n";

        $header  = array("POST ".$url." HTTP/1.1",
                         "Content-Length: ".strlen($xml),
                         "Content-type: text/xml; charset=UTF8",
                         "Connection: close; Keep-Alive",
                        );

        $response = NE_Network::curlRequest($this->settings, $url, $xml, $header, true);

        if ($response){
            $response = XmlFunctions::xmlize($response);
        }
        
        return $response;
    }
}
?>
