<?php

/**
* @version 2.7.14
* @package Joomla 1.7/2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

require_once( JPATH_SITE.'/components/com_dtregister/lib/class.payment.php');

require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/quickbook/xml.php');		

class quickbook extends Payment{ 
	
	var $app_ID = "214983863";
	var $connection_ticket = "TGT-91-k9n8qFZN7crT8tKFU7k_VQ";
	var $app_login = "qbtest.sfbi.com";
	var $app_version = "1.0";
	var $language = 'English';
	
	var $bywebservice = true;
	
	function __construct() { 
    	global $godaddy_hosting,$quickbook_app_ID,$quickbook_app_login,$quickbook_connection_ticket;
		parent::__construct();
		$this->godaddy_hosting = $godaddy_hosting;
		$this->app_ID = $quickbook_app_ID;
		$this->app_login = $quickbook_app_login;
		$this->connection_ticket = $quickbook_connection_ticket;
		$this->host = ($this->paymentmode=='test')?'merchantaccount.ptc.quickbooks.com':'webmerchantaccount.quickbooks.com';
	}
	
	 function billingform(){

	   global $cardtype;
       
	  // $form = parent::billingform();
        ob_start();

	   ?>
	
	   <div id="dtcard_details" style="clear:both; margin:10px 0 0 0">
		
          <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'DT_NAME_ON_CARD' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input type="text" name="billing[NameOnCard]" class="inputbox" value="<?php echo isset($this->NameOnCard)?$this->NameOnCard:''?>" />

		         </dd>

		   </dl>
           
           <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'DT_BILLING_ADDRESS' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input type="text" name="billing[CreditCardAddress]" class="inputbox" value="<?php echo isset($this->CreditCardAddress)?$this->CreditCardAddress:''?>" />

		         </dd>

		   </dl>
           
           <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'DT_BILLING_ZIPCODE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input type="text" name="billing[CreditCardPostalCode]" class="inputbox" value="<?php echo isset($this->CreditCardPostalCode)?$this->CreditCardPostalCode:''?>" />

		         </dd>

		   </dl>
           
           <dl>

		          <dt class="dtlabel"><?php echo JText::_( 'CARD_NUMBER' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		          <dd class="dtfield"><input type="text" name="billing[x_card_num]" class="inputbox" value="<?php echo isset($this->cb_creditcardnumber)?$this->cb_creditcardnumber:''?>" />

		              <br />

		            <?php echo JText::_( 'CARD_NUMBER_EXPLANATION' );?></dd>

		   </dl>

           <?php
        echo   $this->expiry_fields(isset($this->cb_expdate)?$this->cb_expdate:'');
		?>
         <!--dl>

		    <dt class="dtlabel"><?php echo JText::_( 'CARD_EXPIRY_DATE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		    <dd class="dtfield"><input type="text" name="billing[x_exp_date]" value="<?php //echo isset($this->cb_expdate)?$this->cb_expdate:''?>" class="inputbox" />

		            &nbsp;&nbsp;(mm/yy)</dd>

		 </dl-->

           <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'CVV_CODE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input type="text" name="billing[x_card_code]" size="6" class="inputbox" value="<?php echo isset($this->x_card_code)?$this->x_card_code:''; ?>" />

		            <?php echo JText::_( 'CVV_CODE_EXPLANATION' );?></dd>

		   </dl>

       </div>

       <?php

	   $html = ob_get_clean();

	   return $html;

   }
   
   function process () {
	      $year = substr($this->x_exp_date_year,2);
	   $exp_date=$this->x_exp_date_month."/".$year;
	   
       $this->x_exp_date = $exp_date ;
		$card_expiry = $this->x_exp_date;
		$card_expiry = explode("/",$card_expiry);
		 
   		$xmlResponse = new xml('<'.'?xml version="1.0"?'.'>');
		$xmlResponse->head2('<'.'?qbmsxml version="2.0"?'.'>');
		$xmlQBMSXML = $xmlResponse->createTag("QBMSXML");
		$xmlSignonMsgsRq = $xmlResponse->createTag("SignonMsgsRq",array(), '', $xmlQBMSXML);
		$xmlSignonDesktopRq = $xmlResponse->createTag("SignonDesktopRq",array(), '', $xmlSignonMsgsRq);
		$xmlResponse->createTag("ClientDateTime",array(), date('Y-m-d\TH:i:s'),	$xmlSignonDesktopRq);
		$xmlResponse->createTag("ApplicationLogin",array(), $this->app_login, $xmlSignonDesktopRq);
		$xmlResponse->createTag("ConnectionTicket",array(), $this->connection_ticket, $xmlSignonDesktopRq);
		$xmlResponse->createTag("Language",array(), $this->language, $xmlSignonDesktopRq);
		$xmlResponse->createTag("AppID",array(), $this->app_ID,	$xmlSignonDesktopRq);
		$xmlResponse->createTag("AppVer",array(), $this->app_version, $xmlSignonDesktopRq);
		
		$xmlQBMSXMLMsgsRq = $xmlResponse->createTag("QBMSXMLMsgsRq",array(), '', $xmlQBMSXML);
		$xmlCustomerCreditCardAuthRq = $xmlResponse->createTag("CustomerCreditCardChargeRq",array(), '', $xmlQBMSXMLMsgsRq);
		$xmlResponse->createTag("TransRequestID",array(),$this->GetTransRequestID(), $xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("CreditCardNumber",array(), $this->x_card_num, $xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("ExpirationMonth",array(), $card_expiry[0],	$xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("ExpirationYear",array(),  $card_expiry[1],	$xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("IsCardPresent",array(), 'false', $xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("Amount",array(), $this->cart->getAmount(),	$xmlCustomerCreditCardAuthRq);
		//????
		$xmlResponse->createTag("NameOnCard",array(), $this->NameOnCard, $xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("CreditCardAddress",array(), $this->CreditCardAddress, $xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("CreditCardPostalCode",array(), $this->CreditCardPostalCode,	$xmlCustomerCreditCardAuthRq);
		$xmlResponse->createTag("SalesTaxAmount",array(), 0, $xmlCustomerCreditCardAuthRq);
		$sendstring=$xmlResponse->generate();
	//	pr(htmlentities($sendstring));
		$header[] = "Content-type: application/x-qbmsxml";
		$header[] = "Content-length: ".strlen($sendstring);
		$result = $this->doCall( "https://".$this->host.":443/j/AppGateway", $sendstring , $header);
	    
		
		if (empty($result)){
			
			//return false;
		}
		$this->response = trim($result);
		
		return $this->parseResponse();
		
   }
   function GetTransRequestID(){

		$str = session_id();
		$str .= (string)time();

		$TransRequestID = md5($str);

		return($TransRequestID);
	}
   
   function parseResponse(){

		$xmlR = new xml($this->response);
		$xmlR->parse();
		$xmlR->getTag(0, $_tagName, $_tagAttributes, $_tagContents, $_tagTags);
		
		if (strtoupper(trim($_tagName)) != 'QBMSXML') {
             
			return false;
		}
		if (count($_tagTags) == 0) {
			
			return false;
		}
		$SIGNONDESKTOPRSTag = $xmlR->getChildByName(0, "SIGNONMSGSRS");
        
		$xmlR->getTag($SIGNONDESKTOPRSTag, $_tagName, $_tagAttributes, $_tagContents, $_tagTags);
		$ReturnParams = Array();
		$ReturnAtr = array();
		foreach ($_tagTags as $k=>$v){
			$xmlR->getTag($v, $tN, $tA, $tC, $tT);
			$ReturnAtr[strtoupper($tN)] = $tA;
//			$str = ($tN)."=".  trim($tC)."{".$tA."}".chr(13);
//			echo ($str);
			foreach ($tT as $kk=>$vv){
				$xmlR->getTag($vv, $tNN, $tAA, $tCC, $tTT);
				$ReturnParams[strtoupper($tNN)] = $tCC;
//				$str = ($tNN)."=".  trim($tCC).chr(13);
//				echo ($str);
			}

		}
		$QBMSXMLMSGSRSTag = $xmlR->getChildByName(0, "QBMSXMLMSGSRS");

		$xmlR->getTag($QBMSXMLMSGSRSTag, $_tagName, $_tagAttributes, $_tagContents, $_tagTags);
		if (is_array($_tagTags)){
   		foreach ($_tagTags as $k=>$v){
   			$xmlR->getTag($v, $tN, $tA, $tC, $tT);
   			$CustomerCreditCardAuthRsAtr = $tA;
   		}
		}else{
   			$CustomerCreditCardAuthRsAtr = $ReturnAtr['SIGNONDESKTOPRS'];
		}
		
		if (!isset($ReturnAtr['SIGNONDESKTOPRS']['STATUSCODE'])) {
			echo 'Return tag SIGNONDESKTOPRS. Not attribute STATUSCODE ';
			return false;
		}
		if ($ReturnAtr['SIGNONDESKTOPRS']['STATUSCODE']!=0) {
		    echo 'Error! STATUSCODE= '.$ReturnAtr['SIGNONDESKTOPRS']['STATUSCODE'].". ";
			return false;
		}
		if ($ReturnAtr['SIGNONDESKTOPRS']['STATUSSEVERITY']=='ERROR') {
		    echo  'Error! STATUSCODE= '.$ReturnAtr['SIGNONDESKTOPRS']['STATUSCODE'].". ".
									$ReturnAtr['SIGNONDESKTOPRS']['STATUSMESSAGE'] ;
			return false;
		}
		if (($CustomerCreditCardAuthRsAtr['STATUSCODE']!=0)
			&&($CustomerCreditCardAuthRsAtr['STATUSSEVERITY']=='ERROR')){
			echo  'Error! STATUSCODE= '.$CustomerCreditCardAuthRsAtr['STATUSCODE'].". ".
									$CustomerCreditCardAuthRsAtr['STATUSMESSAGE'] ;
			return false;
		}
		
		if ((	$CustomerCreditCardAuthRsAtr['STATUSCODE']==0)
				&&($CustomerCreditCardAuthRsAtr['STATUSSEVERITY']=='INFO')
				&&($CustomerCreditCardAuthRsAtr['STATUSMESSAGE']=='Status OK')){
			foreach ($tT as $kk=>$vv){
				$xmlR->getTag($vv, $tNN, $tAA, $tCC, $tTT);
				$ReturnParams[strtoupper($tNN)] = $tCC;
			}
			
			$this->transactionId = $ReturnParams['CREDITCARDTRANSID'];
            $process = DT_Session::get('Setting.process');
			DT_Session::set($process.'.payment.transactionId',$this->transactionId);
		    $this->responseparts = $ReturnParams;
			return True;

		}
		if (($CustomerCreditCardAuthRsAtr['STATUSCODE']!=0)
			&&($CustomerCreditCardAuthRsAtr['STATUSSEVERITY']=='ERROR')){

/*			foreach ($tT as $kk=>$vv){
				$xmlR->getTag($vv, $tNN, $tAA, $tCC, $tTT);
				$ReturnParams[strtoupper($tNN)] = $tCC;
			}*/
			
			echo  "ERROR:".$CustomerCreditCardAuthRsAtr['STATUSCODE'];
			echo  "MSG:".$CustomerCreditCardAuthRsAtr['STATUSMESSAGE'];

			$error = "Error:".$CustomerCreditCardAuthRsAtr['STATUSCODE'].chr(13)." ".$CustomerCreditCardAuthRsAtr['STATUSMESSAGE'];
			echo  $error ;

			// Catch Transaction ID
//			$d["order_payment_trans_id"] = $ReturnParams['CREDITCARDTRANSID'];

			return false;

		}

		if (empty($ReturnParams['CREDITCARDTRANSID'])){
				echo 'Error! Field CREDITCARDTRANSID is empty!';
			return false;
		}
		return false;

	 }
   function doCall( $url, $postData='', $headers=array()){
 		
		$urlParts = parse_url( $url );
		if( !isset( $urlParts['port'] )) $urlParts['port'] = 80;
		if( !isset( $urlParts['scheme'] )) $urlParts['scheme'] = 'http';

		if( function_exists( "curl_init" )) {

		   // pr($urlParts['scheme'].'://'.$urlParts['host'].':'.$urlParts['port'].$urlParts['path']);

			$CR = curl_init();
			curl_setopt($CR, CURLOPT_URL, $urlParts['scheme'].'://'.$urlParts['host'].':'.$urlParts['port'].$urlParts['path']);

			// just to get sure the script doesn't die
		//	curl_setopt($CR, CURLOPT_TIMEOUT, 50 );
			if( !empty( $headers )) {
				// Add additional headers if provided
			 	curl_setopt($CR, CURLOPT_HTTPHEADER, $headers);
			}
			curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
			//curl_setopt($CR, CURLOPT_FAILONERROR, true);
			if( $postData ) {
				curl_setopt($CR, CURLOPT_POSTFIELDS, $postData );
				curl_setopt($CR, CURLOPT_POST, 1);
			}
			// Do we need to set up the proxy?
			if( $this->godaddy_hosting ) {
				
				//curl_setopt($CR, CURLOPT_HTTPPROXYTUNNEL, true);
				curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);

		  		curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
				
			}

			if( $urlParts['scheme'] == 'https') {
				// No PEER certificate validation...as we don't have
				// a certificate file for it to authenticate the host www.ups.com against!
				curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
				//curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem");
			}
			$result = curl_exec( $CR );
		//	pr($result);
			$error = curl_error( $CR );
		//	pr($error);
			if( !empty( $error ) && stristr( $error, '502') && !empty( $proxyURL )) {
				
				curl_setopt( $CR, CURLOPT_PROXYAUTH, CURLAUTH_NTLM );
				$result = curl_exec( $CR );
				$error = curl_error( $CR );
			}
			curl_close( $CR );

			if( !empty( $error ) && $result == "") {
				echo $error; 
				return false;
			}
			else {
				return $result;
			}
		}else{
			
			return false;
		}
	}
}
?>