<?

# $Id: cardtrans.inc.php 743 2005-11-21 18:45:48Z raf $

require_once("../inc/lphp.php"); # yourpay class
require_once("../inc/htmlfile.inc.php"); # for softgood file
  
function DG_Parser($simple) 
	{
	$p = xml_parser_create();
	xml_parse_into_struct($p,$simple,$vals,$index);
	xml_parser_free($p);

#	echo "<pre>"; print_r($vals); echo "</pre>";

	return $vals[1]["attributes"];
	}

function CCAuth($oid,$cardid,$ccn,$ccexpm,$ccexpy,
	$first,$last,$ad1,$ad2,$city,$state,$zip,
	$phone,$country,$mail,$desc,$sale,$oidval="")
	{


	$DEBUG = 0;

	if (CCAUTH_DEBUG)
		{
		$ret = (CCAUTH_DEBUG == 1 ? "REF" : "AUTH");
		$clog = new Cardlog();

		$clog->setCardID($cardid);
		$clog->setResult($ret);
		$clog->setResult2("DEBUG sale=$sale is " . CCAUTH_DEBUG);
		$clog->setTransactionID($ret == "AUTH" ? rand(0,99999) : "");
		$clog->setOrderID($oid);
		$clog->setAmount($sale);
		$clog->Update();

		return array($ret,"DEBUG is " . CCAUTH_DEBUG . " request:" .
			"$oid,$cardid,$ccn,$ccexpm,$ccexpy," .
			"$first,$last,$ad1,$ad2,$city,$state,$zip," .
			"$phone,$country,$mail,$desc,$sale");
		}

	# if YourPay support is enabled, just call YPCCAuth

	if (YOURPAY_ENABLE)
		return YPCCauth($oid,$cardid,$ccn,$ccexpm,$ccexpy,
        		$first,$last,$ad1,$ad2,$city,$state,$zip,
        		$phone,$country,$mail,$desc,$sale,$oidval);

	$shipping = 0;

	$reqheader = 'xml=<!DOCTYPE pp.request PUBLIC "-//IMALL//DTD' .
		' PUREPAYMENTS 1.0//EN" ' .
		'"http://www.purepayments.com/dtd/purepayments.dtd">';

	$start = '<pp.request merchant="' . SUREPAY_MERCHANTID .
		'" password="' . SUREPAY_PASSWORD . '">';

	$auth = '<pp.auth ordernumber="' . $oid . '" shippingcost="' .
		sprintf("%.02f",$shipping) . 'USD">';

	$exp = sprintf("%02d/%02d",$ccexpm,substr($ccexpy,-2));
	$cvs = "0";

	$creditcard = '<pp.creditcard number="'. $ccn .
		'" expiration="'. $exp . '" cvv2status="0" cvv2="'. $cvs .
		'" ecommerce="true" markforsettle="true">';

	$billaddress = '<pp.address type="billing" firstname="'. $first .
		'" lastname="'. $last . '" address1="' . $ad1 .
		'" address2="' . $ad2 . '" city="' . $city .
		'" state="' . $state . '" zip="' . $zip .
		'" country="' . $country . '" phone="' . $phone .
		'" email="' . $mail . '"/>';

	$shipaddress = '<pp.address type="shipping" firstname="' . $first .
		'" lastname="' . $last . '" address1="' . $ad1 .
		'" address2="' . $ad2 . '" city="' . $city .
		'" state="' . $state . '" zip="' . $zip .
		'" country="' . $country . '" phone="' . $phone .
		'" email="' . $mail . '"/>';

	$sku = '0'; // ???
	$quantity = '1';

	$lineitem = '<pp.lineitem sku="' . $sku .
		'" description="' . $desc .
		'" quantity="' . $quantity .
		'" taxrate="0" unitprice="' . sprintf("%.02f",$sale) . 'USD"/>';

	$request = $reqheader . $start . $auth . $creditcard . $billaddress .
		'</pp.creditcard>' . $shipaddress . $lineitem .
		'</pp.auth></pp.request>';

	if ($DEBUG) echo "<pre>request=", wordwrap(htmlentities($request),70), "</pre>";

	$ret = "AUTH";

	$ch = curl_init ();

	curl_setopt($ch, CURLOPT_URL, SUREPAY_POST);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
#	curl_setopt($ch, CURLOPT_POSTFIELDSIZE, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, SUREPAY_TIMEOUT); 
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_SSLVERSION, 3);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	$result = curl_exec ($ch);
/*
	$result = '<!DOCTYPE pp.response PUBLIC "-//IMALL//DTD ' .
	'PUREPAYMENTS 1.0//EN" "http://www.purepayments.com/dtd/purepayments.dtd">' .
	'<pp.response><pp.authresponse merchant="21641" ordernumber="234614" ' .
	'transactionid="CC_NP37A284B25B" authcode="005171" avs="YYY" cvv2result="P" ' .
	'authstatus="AUTH"/></pp.response>';
*/

	if ($DEBUG) echo "<pre>got=" . htmlspecialchars($result) . "</pre>";

	$curl_array = curl_getinfo($ch);

/* When you're testing, the XML string indicates that a card is authorized
(AUTH), declined (DCL) or referred (REF), according to the credit card
number (you must use Visa 4012000033330026) and total order amount (total =
the amount the customer would see on their charge card).

$11 = "AUTH"
$21 = "REF"
$31 = "DCL".  

Anything else should give you an error indicated by "ERR". */

	$attributes = dg_parser($result);

	if ($DEBUG)
		{
		foreach ($attributes as $k => $v)
			echo "ATTR $k = '$v'<br>";
		}

	$transid = (isset($attributes["TRANSACTIONID"]) ?
		$attributes["TRANSACTIONID"] : "");

	$ret = (isset($attributes["AUTHSTATUS"]) ?
		$attributes["AUTHSTATUS"] : "");

	curl_close ($ch);

	$r = array("UNKN","UNKNOWN");

	switch ($ret)
		{
		case "AUTH":
			$r = array("AUTH","OK");
			break;
		case "REF":
			$r = array("REF","Referal");
			break;
		case "DCL":
			$r = array("DCL","Declined");
			break;
		case "ERR":
			$r = array("ERR","Surepay error");
			break;
		default:
			//$r = array("INT","Internal error: " . $attributes[1]);
			$r = array("INT","Invalid Card Number");
			break;
		}

	# do not check return code; this is a cruicial function

	$clog = new Cardlog();

	$clog->setCardID($cardid);
	$clog->setResult($r[0]);
	$clog->setResult2($r[1]);
	$clog->setTransactionID($transid);
	$clog->setOrderID($oid);
	$clog->setAmount($sale);
	$clog->Update();

	return $r;
	}

function YPCCAuth($oid,$cardid,$ccn,$ccexpm,$ccexpy,
	$first,$last,$ad1,$ad2,$city,$state,$zip,
	$phone,$country,$mail,$desc,$sale,$oidval="")
	{
	global $_SERVER;

	$htmls = new HTMLFile();
	$html_file = basename($htmls->makeFilename($first . " " . $last));

	$fmtd_sale =sprintf("%.02f",$sale);
	$fmtd_expy = sprintf("%02d",substr($ccexpy,-2));
	$fmtd_expm = sprintf("%02d",$ccexpm);
	$fmtd_adrn = preg_replace("/[^0-9]/", "", $ad1 . $ad2);
	$fmtd_ip = $_SERVER["REMOTE_ADDR"];

	$yp = new lphp();

	$order = array(
		"host" => YOURPAY_HOST,
		"port" => YOURPAY_PORT,
		"keyfile" => YOURPAY_PEM,
		"configfile" => YOURPAY_STORENO,
		"terminaltype" => "UNSPECIFIED",
		"ordertype" => "SALE",
		);

	$order["debugging"] = "false";
	$order["debugging"] = (CCAUTH_DEBUG ? "true" : "false");

	$order["oid"] = YOURPAY_OIDPREFIX . "$oid";
	if (strlen($oidval)) $order["oid"] = $oidval;
	$order["oid"] = $order["oid"] . "-" . sprintf("%03d",rand(0,999));
	$order["ip"] = $fmtd_ip;

	$order["chargetotal"] = $fmtd_sale;

	$order["cardnumber"] = $ccn;
	$order["cardexpmonth"] = $fmtd_expm;
	$order["cardexpyear"] = $fmtd_expy;
#	$order["cvmindicator"] = "provided";
#	$order["cvmvalue"] = $cvs;

	$order["name"] = $first . " " . $last;
	$order["address1"] = $ad1;
	$order["address2"] = $ad2;
	$order["city"] = $city;
	$order["state"] = $state;
	$order["zip"] = $zip;
	$order["country"] = $country;
	$order["phone"] = $phone;
	$order["email"] = $mail;
	$order["addrnum"] = $fmtd_adrn;

	$order["sname"] = $first . " " . $last;
	$order["saddress1"] = $ad1;
	$order["saddress2"] = $ad2;
	$order["scity"] = $city;
	$order["sstate"] = $state;
	$order["szip"] = $zip;
	$order["scountry"] = $country;

	$items = array(
		"id" => YOURPAY_ITEMID,
		"description" => $desc,
		"quantity" => "1",
		"price" => $fmtd_sale,
		"esdtype" => "softgood",
		"softfile" => $html_file,
		);


	$order["items"][0] = $items;

	$ret = $yp->curl_process($order);

#	var_dump($ret);

	$r = array("UNKN","UNKNOWN");
	$transid = "FAILED-" . simuniqueid();

	switch ($ret["r_approved"])
		{
		case "APPROVED":
			$r = array("AUTH","OK");
			$transid = $order["oid"];
			break;
		case "FRAUD":
			$r = array("REF",$ret["r_error"]);
			$transid = $order["oid"];
			break;
		case "FAILURE":
			$r = array("FAIL","Could not connect");
			break;
		case "DECLINED":
			$r = array("DCL",$ret["r_error"]);
			$transid = $order["oid"];
			break;
/*
			case "ERR":
				$r = array("ERR","Surepay error");
				break;
*/
		default:
			$r = array("INT","Internal error: " . $ret["r_error"]);
#			$r = array("INT","Invalid Card Number");
			break;
		}

	$clog = new Cardlog();

	$clog->setCardID($cardid);
	$clog->setResult($r[0]);
	$clog->setResult2($r[1]);
	$clog->setTransactionID($transid);
	$clog->setOrderID($oid);
	$clog->setAmount($sale);
	$clog->Update();

	return $r;
	}

/*
# THIS IS DEBUG CODE

require_once("../conf/db.config.php");
require_once("../inc/database.inc.php");
require_once("../inc/layout.inc.php");
require_once("../inc/macro.inc.php");
require_once("../inc/mailmsgs.inc.php");

require_once("../inc/nicefunctions.inc.php");

require_once("../inc/client.inc.php");
require_once("../inc/order.inc.php");
require_once("../inc/resinfo.inc.php");
require_once("../inc/card.inc.php");
require_once("../inc/assigment.inc.php");
require_once("../inc/autoassign.inc.php");
require_once("../inc/autoassignlog.inc.php");
require_once("../inc/package.inc.php");
require_once("../inc/rush.inc.php");
require_once("../inc/resfile.inc.php");

require_once("../inc/prices.inc.php");
require_once("../inc/writer.inc.php");

#require_once("../inc/cardtrans.inc.php");
require_once("../inc/cardlog.inc.php");

require_once("../inc/comment.inc.php");

require_once("../inc/website.inc.php");

require_once("../inc/coupon.inc.php");
require_once("../conf/resconfig.php");

$db = new Database($RES_DB_DATABASE,$RES_DB_HOST,$RES_DB_USER,$RES_DB_PASS);

print_r(CCAuth(219384,"123",1,1,1,
	1,1,1,1,1,1,1,
	1,1,1,1,1));
*/
