<?php

/**
* @version 2.7.18
* @package Joomla 1.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');

class worldpay extends Payment{

   var $last_error;                 // holds the last error encountered

   var $ipn_log;                    // bool: log IPN results to text file?

   var $ipn_log_file;               // filename of the IPN log

   var $ipn_response;               // holds the IPN response from worldpay

   var $ipn_data = array();         // array contains the POST values for IPN

   var $fields = array();           // array holds the fields to submit to worldpay

   var $bywebservice = false;
   
   var $return_notify_html =  true;

   function __construct() {

      // initialization constructor.  Called when class is created.

      parent::__construct();
         
      global $worldpay_instId;
      $this->host = ($this->paymentmode=='test')?'secure-test.worldpay.com':'secure.worldpay.com';

      $this->last_error = '';

      $this->ipn_log_file = 'ipn_log.txt';

      $this->ipn_log_file = dirname(__FILE__)."/ipnlog.txt";
	  //pr($this->ipn_log_file);

      $this->ipn_log = true;

      $this->ipn_response = '';  
      if($this->paymentmode=='test'){
	  	 $this->add_field('testMode',100 ); 
	  }
      $this->add_field('instId',$worldpay_instId );       

   }

   function add_field($field, $value) {

      $this->fields["$field"] = $value;

   }

   function process(){

	   global $currency_code,$Itemid;

	   $mosConfig_live_site = JURI::root( false );

	   if($currency_code==""){$currency_code='USD';}

	   $session_id = $this->saveSession();
	
	   $this->add_field('MC_callback', "{$mosConfig_live_site}components/com_dtregister/success.php?return=$session_id&Itemid=$Itemid&task=notification");
	   
	   $this->add_field('desc',$this->description);
	   
       $this->add_field('cartId', $session_id);
	  
	   if(isset($this->firstname) && $this->firstname !="" ){
	  	  $this->add_field('name', trim($this->firstname." ".$this->lastname));
	   }
	  
	   if(isset($this->email) && $this->email !="" ){
	  	  $this->add_field('email', $this->email);
	   }
	    if(isset($this->address) && $this->address !="" ){
	  	 $this->add_field('address1', $this->address);
	  }
	  
	   if(isset($this->city) && $this->city !="" ){
	  	 $this->add_field('town', $this->city);
	  }
	  if(isset($this->state) && $this->state !="" ){
	  	 $this->add_field('region', $this->state);
	  }
	  
	   if(isset($this->zip) && $this->zip !="" ){
	  	 $this->add_field('postcode', $this->zip);
	  }
	  
	    if(isset($this->country) && $this->country !="" ){
	  	 $this->add_field('country', $this->country);
	  }
	  
	   if(isset($this->phone) && $this->phone !="" ){
	  	 $this->add_field('tel', $this->phone);
	  }
	  
	   $this->add_field('amount', $this->cart->getAmount());

	   $this->add_field('currency', "$currency_code");

	   $this->submit_post();

   }

   function submit_post() {

      echo "<center><h3>".JText::_( 'DT_WORLDPAY_REDIRECT_MSG')."</h3></center>\n";

      echo "<form method=\"post\" name=\"formRegister\" action=\"https://".$this->host."/wcc/purchase\">\n";

      foreach ($this->fields as $name => $value) {

         echo " <input type=\"hidden\" name=\"$name\" value=\"$value\"><br />";

      }

?>

		<script language="javascript">

			function rg_direc_to_gateway(){

				document.formRegister.submit();

			}

			setTimeout("rg_direc_to_gateway()",5000);

		</script>

<?php

      echo "</form>\n";

   }

   function validate_ip() {
      $validHosts = array(
        'www.payfast.co.za',
        'sandbox.payfast.co.za',
        'w1w.payfast.co.za',
        'w2w.payfast.co.za',
        );
 
        $validIps = array();
 
        foreach( $validHosts as $pfHostname )
        {
            $ips = gethostbynamel( $pfHostname );

            if( $ips !== false )
                $validIps = array_merge( $validIps, $ips );
        }
 
    // Remove duplicates
        $validIps = array_unique( $validIps );
 
        if( !in_array( $_SERVER['REMOTE_ADDR'], $validIps ) )    {
            return false;
        } else {
           return true;
        }
   }
   
   function log_ipn_results($success) {
     // return;
      // if (!$this->ipn_log) return;  // is logging turned off?

      // Timestamp

      $text = '['.date('m/d/Y g:i A').'] - ';

      // Success or failure being logged?

      if ($success) $text .= "SUCCESS!\n";

      else $text .= 'FAIL: '.$this->last_error."\n";

      // Log the POST variables

      $text .= "IPN POST Vars from Worldpay:\n";

      foreach ($this->ipn_data as $key=>$value) {

         $text .= "$key=$value, \n";

      }

      // Log the response from the worldpay server

      $text .= "\nIPN Response from Worldpay Server:\n ".$this->ipn_response;

      // Write to log

      $fp=fopen($this->ipn_log_file,'a');

      fwrite($fp, $text . "\n\n");

      fclose($fp);  // close file

   }

   function dump_fields() {

      echo "<h3>worldpay_class->dump_fields() Output:</h3>";

      echo "<table width=\"95%\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">

            <tr>

               <td bgcolor=\"black\"><b><font color=\"white\">Field Name</font></b></td>

               <td bgcolor=\"black\"><b><font color=\"white\">Value</font></b></td>

            </tr>";

      ksort($this->fields);

      foreach ($this->fields as $key => $value) {

         echo "<tr><td>$key</td><td>".urldecode($value)."&nbsp;</td></tr>";

      }

      echo "</table><br>";

   }
   
   function notify(){
	    global $Itemid;
	     $mosConfig_live_site = JURI::root( false );
		 $session_id = $_REQUEST['return'];
		 global $Itemid;
	   if ($_POST['transStatus'] == 'Y') { 
	   	  $pass = false;
	  
	  ?>
      <WPDISPLAY ITEM=banner>
<p>&nbsp;</p>

<meta http-equiv="refresh" content="0;url=<?php echo "{$mosConfig_live_site}success.php?return=$session_id&Itemid=$Itemid&task=restore" ?>">

<form action="<?php echo "{$mosConfig_live_site}success.php?return=$session_id&Itemid=$Itemid&task=restore" ?>" method="post">
	<div align="center">
	  <input name="submit" type="submit" value="<?php echo JText::_('DT_CONTINUE'); ?>" />
    </div>
</form>

<?php
	   
	  // if($this->validate_ip()){
		   $this->transactionId = $_REQUEST['transId'];

		   DT_Session::set('register.payment.transactionId', $this->transactionId);
		   
		   return true;
	  // }else{
		  // return false;
	  // }
	      
   } 
   else {
	   ?>
     
<WPDISPLAY ITEM=banner>
<p>&nbsp;</p>
<meta http-equiv="refresh" content="0;url="<?php echo  "{$mosConfig_live_site}success.php?return=$session_id&Itemid=$Itemid&task=cancel" ?>" >

<!-- form action="<?php echo "{$mosConfig_live_site}success.php?return=$session_id&Itemid=$Itemid&task=cancel" ?>" method="post">
	<div align="center">
	  <input name="submit" type="submit" value="<?php echo JText::_('DT_CANCEL'); ?>" />
    </div>
</form-- >

       <?php
	  
   	  return false;
   }
}

}