<?php
/**
 * WebMoney system routines
 * 30.01.2007
 */
require_once(dirname(__FILE__) . "/money_config.php");
require_once(dirname(__FILE__) . "/xml2array.class.php");
require_once(dirname(__FILE__) . "/array2xml.class.php");

class WMSystem
{
	/* формирование подписи WMSigner */
	function sign($inStr)
	{
		global $WM;

		$descriptorspec = array(
		0 => array("pipe", "r"),
		1 => array("pipe", "w"),
		2 => array("pipe", "w") );
		$process = proc_open($WM['signer_path'], $descriptorspec, $pipes);
		
		if (is_resource($process))
		{
			fwrite($pipes[0], $inStr."\004\r\n");
			fclose($pipes[0]);
			$s = fread($pipes[1], 133);
			fclose($pipes[1]);

			$return_value = proc_close($process);
			
			return $s;
		}
	}

	/* request number */
	function requestNumber()
	{
		return time();
	}

	/* http Request to WM server*/
	function httpRequest($url, $data)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);

		$fp = tmpfile();
		curl_setopt ($ch, CURLOPT_FILE, $fp);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_exec($ch);
		curl_close($ch);

		fseek($fp, 0, SEEK_SET);
		$result = fgets($fp, 10240);
		fclose($fp);

		return $result;
	}
	
	/* http Request to WM server with Certificate */
	function httpRequestWCert($url, $data)
	{
		global $WM;
		
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // ? 
		//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // ?
		// root cert WebMoney CA:
		curl_setopt($ch, CURLOPT_CAINFO, $WM['wm_CAcert']);
		
		curl_setopt($ch, CURLOPT_SSLKEY, $WM['wm_key']);
		curl_setopt($ch, CURLOPT_SSLKEYPASSWD , $WM['wm_pass']);
		curl_setopt($ch, CURLOPT_SSLCERT, $WM['wm_cert']);
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		
		// exec request
		$result = curl_exec($ch);
		if (curl_errno($ch) != 0)
		{
		    die('CURL_error: ' . curl_errno($ch) . ', ' . curl_error($ch));
		};
		curl_close($ch);
						
		return $result;
	}

	function startElement($parser, $name, $attrs){
		global $xmlTag;
		$xmlTag = $name;
	}

	function endElement($parser, $name){}

	function characterData($parser, $data)
	{
		global $tmp_xml_res;
		global $xmlTag;
		global $tmp_res_arr;

		if(strtoupper($xmlTag)=="PURSENAME"){
			$tmp_xml_res = strtoupper($data);
		}

		if(strtoupper($xmlTag)=="AMOUNT"){
			if($tmp_xml_res!=""&&$data!=""){
				$tmp_res_arr[$tmp_xml_res] = (trim($data)+0);
			}
			$tmp_xml_res = "";
		}
	}

	/* get Amount request */
	function getAmount($wm_id)
	{
		global $WM;
		
		// request to WM server
		$reqn = WMSystem::requestNumber();
		if ($WM['auth_type'] == WM_AUTH_TYPE_SIGNER)
			$xml = WMSystem::getAmountRequest_Signer($wm_id, $reqn);
		else
			$xml = WMSystem::getAmountRequest_Cert($wm_id, $reqn);
		
		// response parsing
		if($xml=="")
		{
			return false;
		}
		
		$xml2array = new Xml2Array($xml);
		
		if(!$xml2array->parse())
		{
			return false;
		}
		
		$array = $xml2array->getArray();

		if($array["root"] != "w3s.response" || $array["reqn"] != $reqn || $array["purses"]["attributes"]["wmid"] != $wm_id)
		{
			return false;
		}
		
		if($array["retval"] != "0")
		{
			return false;
		}
		
		$count = (integer)$array["purses"]["attributes"]["cnt"];
		
		$result = array();
		if($count > 0)
		{
			foreach($array["purses"]["purse"] as $purse)
			{
				$result[$purse["pursename"]] = $purse["amount"];
			}
		}
		
		return $result;
	}
	
	function getAmountRequest_Signer($wm_id, $reqn)
	{
		global $WM;

		$url = "https://w3s.webmoney.ru/asp/XMLPurses.asp";
		$sign = WMSystem::sign($wm_id.$reqn);
		
		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><sign>$sign</sign><getpurses><wmid>$wm_id</wmid></getpurses></w3s.request>";
		
		$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");
		
		return $xml;
 	}
	
	function getAmountRequest_Cert($wm_id, $reqn)
	{
		global $WM;

		$url = "https://w3s.webmoney.ru/asp/XMLPursesCert.asp";

		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><getpurses><wmid>$wm_id</wmid></getpurses></w3s.request>";
		
		$xml = WMSystem::httpRequestWCert($url, $str);
		
		return $xml;
 	}
	/* ------------------------- */

	
	/* check order request 
	function checkOrder($order_id, $wm_order_id, $from_purse)
	{
		global $WM;
		
		// request to WM server
		$reqn = WMSystem::requestNumber();
		if ($WM['auth_type'] == WM_AUTH_TYPE_SIGNER)
			$xml = WMSystem::getAmountRequest_Signer($wm_id, $reqn);
		else
			$xml = WMSystem::getAmountRequest_Cert($wm_id, $reqn);

		// parsing response
		
	}
	
	function checkOrderRequest_Signer($order_id, $wm_order_id, $from_purse, $reqn)
	{
		$url = "https://w3s.webmoney.ru/asp/XMLPurses.asp";
		$sign = WMSystem::sign($wm_id.$reqn);

		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['signer_id']."</wmid><sign>$sign</sign><getpurses><wmid>$wm_id</wmid></getpurses></w3s.request>";
		
		$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");
		
		return $xml;
		<w3s.request>  <reqn></reqn>  <wmid></wmid>  <sign></sign>  <getoperations>  <purse></purse>  <wmtranid></wmtranid>  <tranid></tranid>  <wminvid></wminvid>  <orderid></orderid>  <datestart></datestart>  <datefinish></datefinish>  </getoperations> </w3s.request>

		$url = "https://w3s.webmoney.ru/asp/GetTran.asp?CTID=$order_id&WTID=$wm_order_id&P=$from_purse&RN=$reqn&SS=".WMSystem::sign($wm_order_id.$order_id.$from_purse.$reqn);

		$res = WMSystem::httpRequest($url);

		return $res;
	}
	
	function checkOrderRequest_Cert($order_id, $wm_order_id, $from_purse, $reqn)
	{
		$reqn = WMSystem::requestNumber();

		$url = "https://w3s.webmoney.ru/asp/GetTran.asp?CTID=$order_id&WTID=$wm_order_id&P=$from_purse&RN=$reqn&SS=".WMSystem::sign($wm_order_id.$order_id.$from_purse.$reqn);

		$res = WMSystem::httpRequest($url);

		return $res;
	}*/
	
	function checkOrder($order_id, $wm_order_id, $from_purse)
	{
		$reqn = WMSystem::requestNumber();

		$url = "https://w3s.webmoney.ru/asp/GetTran.asp?CTID=$order_id&WTID=$wm_order_id&P=$from_purse&RN=$reqn&SS=".WMSystem::sign($wm_order_id.$order_id.$from_purse.$reqn);

		$res = WMSystem::httpRequest($url);

		// parsing response
		if (substr($res,0,10) == "TranState:")
		{
			$result = sprintf("%d", substr($res,10));

			if($result > 0 ){
				return true;
			}
		}

		return false;
	}
	/* --------------------- */
	
	
	/* check purse request */
	function checkPurse($wm_id, $purse)
	{
		global $WM;
		
		// request to WM server
		$reqn = WMSystem::requestNumber();
		if ($WM['auth_type'] == WM_AUTH_TYPE_SIGNER)
			$xml = WMSystem::checkPurse_Signer($wm_id, $purse, $reqn);
		else
			$xml = WMSystem::checkPurse_Cert($wm_id, $purse, $reqn);
		
		// parse request
		if($xml=="")
		{
			return false;
		}
		
		$xml2array = new Xml2Array($xml);
		
		if(!$xml2array->parse())
		{
			return false;
		}
		
		$array = $xml2array->getArray();

		if($array["root"] != "w3s.response" || $array["reqn"] != $reqn)
		{
			return false;
		}
		
		if($array["retval"] != "0")
		{
			return false;
		}
		else
			return true;
	}
	
	function checkPurse_Signer($wm_id, $purse, $reqn)
	{
		global $WM;
		
		$url = "https://w3s.webmoney.ru/asp/XMLFindWMPurse.asp";
		
		$sign = WMSystem::sign($wm_id.$purse);
		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><sign>$sign</sign><testwmpurse><wmid>$wm_id</wmid><purse>$purse</purse></testwmpurse></w3s.request>";
		
		$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");
		
		return $xml;
	}
	
	function checkPurse_Cert($wm_id, $purse, $reqn)
	{
		global $WM;

		$url = "https://w3s.wmtransfer.com/asp/XMLFindWMPurseCert.asp";

		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><testwmpurse><wmid>$wm_id</wmid><purse>$purse</purse></testwmpurse></w3s.request>";
		
		$xml = WMSystem::httpRequestWCert($url, $str);
		
		return $xml;
	}
	/* -------------------------- */

	
	/* check Inv request */
	function checkInv($order_id, $inv_id, $store_purse, $amount)
	{
		global $WM;
		
		// request to WM server
		$reqn = WMSystem::requestNumber();
		if ($WM['auth_type'] == WM_AUTH_TYPE_SIGNER)
			$xml = WMSystem::checkInvRequest_Signer($order_id, $inv_id, $store_purse, $amount, $reqn);
		else
			$xml = WMSystem::checkInvRequest_Cert($order_id, $inv_id, $store_purse, $amount, $reqn);
		
		// parse request
		if($xml=="")
		{
			return false;
		}
		
		$xml2array = new Xml2Array($xml);
		
		if(!$xml2array->parse())
		{
			return false;
		}
		
		$array = $xml2array->getArray();

		if($array["root"] != "w3s.response" || $array["reqn"] != $reqn)
		{
			return false;
		}
		
		if($array["retval"] != "0")
		{
			return false;
		}
		
		$count = (integer)$array["operations"]["attributes"]["cnt"];
		
		if($count > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function checkInvRequest_Signer($order_id, $inv_id, $store_purse, $amount, $reqn)
	{
		global $WM;
		
		$url = "https://w3s.webmoney.ru/asp/XMLOperations.asp";
		
		$sign = WMSystem::sign($store_purse.$reqn);
		
		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><sign>$sign</sign><getoperations><purse>$store_purse</purse><wmtranid></wmtranid><tranid></tranid><wminvid>$inv_id</wminvid><orderid>$order_id</orderid><datestart>".date("Ymd H:i:s", time() - 3600*24*3)."</datestart><datefinish>".date("Ymd H:i:s", time() + 3600*24*3)."</datefinish></getoperations></w3s.request>";
		
		$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");
		
		return $xml;
	}
	
	function checkInvRequest_Cert($order_id, $inv_id, $store_purse, $amount, $reqn)
	{
		global $WM;

		$url = "https://w3s.webmoney.ru/asp/XMLOperationsCert.asp";

		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><getoperations><purse>$store_purse</purse><wmtranid></wmtranid><tranid></tranid><wminvid>$inv_id</wminvid><orderid>$order_id</orderid><datestart>".date("Ymd H:i:s", time() - 3600*24*3)."</datestart><datefinish>".date("Ymd H:i:s", time() + 3600*24*3)."</datefinish></getoperations></w3s.request>";
		
		$xml = WMSystem::httpRequestWCert($url, $str);
		
		return $xml;
	}
	/* --------------------- */

	
	/* transfer request */
	function transfer($amount, $purse_from, $purse_to, $order_id, $desc)
	{
		global $WM;
		
		// request to WM server
		$reqn = WMSystem::requestNumber();
		if ($WM['auth_type'] == WM_AUTH_TYPE_SIGNER)
			$xml = WMSystem::transferRequest_Signer($amount, $purse_from, $purse_to, $order_id, $desc, $reqn);
		else
			$xml = WMSystem::transferRequest_Cert($amount, $purse_from, $purse_to, $order_id, $desc, $reqn);
		mail('dmitry.revenko@businessmedia.ru', 'transfer', $xml);
		// parsing response
		if($xml=="")
		{
			return false;
		}
		
		$xml2array = new Xml2Array($xml);
		
		if(!$xml2array->parse())
		{
			return false;
		}
		
		$array = $xml2array->getArray();
			
		if($array["root"] != "w3s.response" || $array["reqn"] != $reqn)
		{
			return false;
		}
		
		if($array["retval"] != "0")
		{
			return false;
		}
		
		$result = $array["operation"];
		$result["id"] = $result["attributes"]["id"];
		unset($result["attributes"]);
		
		return $result;
	}
	
	function transferRequest_Signer($amount, $purse_from, $purse_to, $order_id, $desc, $reqn)
	{
		global $WM;

		$url = "https://w3s.webmoney.ru/asp/XMLTrans.asp";
		
		$sign = WMSystem::sign($reqn.$order_id.$purse_from.$purse_to.$amount."0"."".$desc."0");
		
		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><sign>$sign</sign><trans>
		<tranid>$order_id</tranid>
		<pursesrc>$purse_from</pursesrc>
		<pursedest>$purse_to</pursedest>
		<amount>$amount</amount>
		<period>0</period>
		<pcode></pcode>
		<desc>$desc</desc>
		<wminvid>0</wminvid>
		</trans></w3s.request>";
		
		$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");
		
		return $xml;
	}
	
	function transferRequest_Cert($amount, $purse_from, $purse_to, $order_id, $desc, $reqn)
	{
		global $WM;

		$url = "https://w3s.webmoney.ru/asp/XMLTransCert.asp";
		
		$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><trans>
		<tranid>$order_id</tranid>
		<pursesrc>$purse_from</pursesrc>
		<pursedest>$purse_to</pursedest>
		<amount>$amount</amount>
		<period>0</period>
		<pcode></pcode>
		<desc>$desc</desc>
		<wminvid>0</wminvid>
		</trans></w3s.request>";
		
		$xml = WMSystem::httpRequestWCert($url, $str);
		
		return $xml;
	}
	/* ------------------ */
}

?>