<?php
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
/**
* @version $Id: ps_eway.php,v 1.5 2005/01/27 19:33:57 soeren_nb Exp $
* @package mambo-phpShop
* @subpackage Payment
* @copyright (C) 2004-2005 Soeren Eberhardt
*
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* mambo-phpShop is Free Software.
* mambo-phpShop comes with absolute no warranty.
*
* www.mambo-phpshop.net
*
* The ps_eway class.
*
*/

class ps_eway {

    var $classname = "ps_eway";
    var $payment_code = "EWAY";
    
    /**
    * Show all configuration parameters for this payment method
    * @returns boolean False when the Payment method has no configration
    */
    function show_configuration() {
        global $PHPSHOP_LANG;
        $db = new ps_DB();
        
        /** Read current Configuration ***/
        include_once(CLASSPATH ."payment/".$this->classname.".cfg.php");
    ?>
    <table>
        <tr>
        <td><strong>eWay Customer ID</strong></td>
            <td>
                <input type="text" name="EWAY_CUSTID" class="inputbox" value="<?  echo EWAY_CUSTID ?>" />
            </td>
            <td>The Customer ID you received from eWay.
            </td>
        </tr>
        <tr>
            <td><strong><?php echo $PHPSHOP_LANG->_PHPSHOP_PAYMENT_CVV2 ?></strong></td>
            <td>
                <select name="EWAY_CHECK_CARD_CODE" class="inputbox">
                <option <?php if (EWAY_CHECK_CARD_CODE == 'YES') echo "selected=\"selected\""; ?> value="YES">
                <?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_YES ?></option>
                <option <?php if (EWAY_CHECK_CARD_CODE == 'NO') echo "selected=\"selected\""; ?> value="NO">
                <?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_NO ?></option>
                </select>
            </td>
            <td><?php echo $PHPSHOP_LANG->_PHPSHOP_PAYMENT_CVV2_TOOLTIP ?></td>
        </tr>
        <tr>
            <td><strong>Order Status for successful transactions</strong></td>
            <td>
                <select name="EWAY_VERIFIED_STATUS" class="inputbox" >
                <?php
                    $q = "SELECT order_status_name,order_status_code FROM #__pshop_order_status ORDER BY list_order";
                    $db->query($q);
                    $order_status_code = Array();
                    $order_status_name = Array();
                    
                    while ($db->next_record()) {
                      $order_status_code[] = $db->f("order_status_code");
                      $order_status_name[] =  $db->f("order_status_name");
                    }
                    for ($i = 0; $i < sizeof($order_status_code); $i++) {
                      echo "<option value=\"" . $order_status_code[$i];
                      if (EWAY_VERIFIED_STATUS == $order_status_code[$i]) 
                         echo "\" selected=\"selected\">";
                      else
                         echo "\">";
                      echo $order_status_name[$i] . "</option>\n";
                    }?>
                    </select>
            </td>
            <td>Select the order status to which the actual order is set, if the eWay Transaction was successful. 
            If using download selling options: select the status which enables the download (then the customer is instantly notified about the download via e-mail).
            </td>
        </tr>
            <tr>
            <td><strong>Order Status for failed transactions</strong></td>
            <td>
                <select name="EWAY_INVALID_STATUS" class="inputbox" >
                <?php
                    for ($i = 0; $i < sizeof($order_status_code); $i++) {
                      echo "<option value=\"" . $order_status_code[$i];
                      if (EWAY_INVALID_STATUS == $order_status_code[$i]) 
                         echo "\" selected=\"selected\">";
                      else
                         echo "\">";
                      echo $order_status_name[$i] . "</option>\n";
                    } ?>
                    </select>
            </td>
            <td>Select an order status for failed eWay transactions.</td>
        </tr>
        <tr>
            <td><strong><?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE ?></strong></td>
            <td>
                <select name="EWAY_TEST_REQUEST" class="inputbox" >
                <option <?php if (EWAY_TEST_REQUEST == 'TRUE') echo "selected=\"selected\""; ?> value="TRUE"><?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_YES ?></option>
                <option <?php if (EWAY_TEST_REQUEST == 'FALSE') echo "selected=\"selected\""; ?> value="FALSE"><?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_NO ?></option>
                </select>
            </td>
            <td><?php echo $PHPSHOP_LANG->_PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE_EXPLAIN ?>
            </td>
        </tr>
      </table>
    <?php
    }
    
    function has_configuration() {
      // return false if there's no configuration
      return true;
   }
   
  /**
	* Returns the "is_writeable" status of the configuration file
	* @param void
	* @returns boolean True when the configuration file is writeable, false when not
	*/
   function configfile_writeable() {
      return is_writeable( CLASSPATH."payment/".$this->classname.".cfg.php" );
   }
   
  /**
	* Returns the "is_readable" status of the configuration file
	* @param void
	* @returns boolean True when the configuration file is writeable, false when not
	*/
   function configfile_readable() {
      return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" );
   }
   
  /**
	* Writes the configuration file for this payment method
	* @param array An array of objects
	* @returns boolean True when writing was successful
	*/
   function write_configuration( &$d ) {
      
      $my_config_array = array("EWAY_CUSTID" => $d['EWAY_CUSTID'],
                                              "EWAY_CHECK_CARD_CODE" => $d['EWAY_CHECK_CARD_CODE'],
                                              "EWAY_VERIFIED_STATUS" => $d['EWAY_VERIFIED_STATUS'],
                                              "EWAY_INVALID_STATUS" => $d['EWAY_INVALID_STATUS'],
                                              "EWAY_TEST_REQUEST" => $d['EWAY_TEST_REQUEST']
                                      );
      $config = "<?php\n";
      $config .= "defined('_VALID_MOS') or die('Direct Access to this location is not allowed.'); \n\n";
      foreach( $my_config_array as $key => $value ) {
        $config .= "define ('$key', '$value');\n";
      }
      
      $config .= "?>";
  
      if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) {
          fputs($fp, $config, strlen($config));
          fclose ($fp);
          return true;
     }
     else
        return false;
   }
   
  /**************************************************************************
  ** name: process_payment()
  ** returns: 
  ***************************************************************************/
   function process_payment($order_number, $order_total, &$d) {
        global $vendor_name, $PHPSHOP_LANG;
        $auth = $_SESSION['auth'];
        
        /*** Get the Configuration File for eway ***/
        require_once(CLASSPATH ."payment/".$this->classname.".cfg.php");
        
        /* eWAY Gateway Location (URI) */
        if( EWAY_TEST_REQUEST == "FALSE" )
            define( "GATEWAY_URL", "https://www.eway.com.au/gateway/xmlpayment.asp");
        else
            define( "GATEWAY_URL", "https://www.eway.com.au/gateway/xmltest/testpage.asp");
            
        // Get user billing information
        $db = new ps_DB;
        $qt = "SELECT * FROM #__users WHERE id='".$auth["user_id"]."' AND address_type='BT'";
        $db->query($qt);
        $db->next_record();
        
        // WE need the $order_total in cents!
        $order_total = $order_total * 100;
        
        // We need to show the year with two digits only
        $year = substr( $_SESSION['ccdata']['order_payment_expire_year'], 0, 2 );
        
        $transaction = new electronic_payment (
                                EWAY_CUSTID, 
                                $order_total, 
                                $db->f("first_name"), 
                                $db->f("last_name"),
                                $db->f("email"), 
                                $db->f("address_1"), 
                                $db->f("zip"), 
                                $vendor_name." Order",
                                $order_number, 
                                $_SESSION['ccdata']['order_payment_name'], 
                                $_SESSION['ccdata']['order_payment_number'], 
                                $_SESSION['ccdata']['order_payment_expire_month'], 
                                $year,
                                $_SESSION['ccdata']['credit_card_code']
                            );
        switch ($transaction->trxn_status()) {
            case "False": 
                    $d["error"] = $PHPSHOP_LANG->_PHPSHOP_PAYMENT_ERROR.": ";
                    $d["error"] .= $transaction->trxn_error();
                    // Catch Transaction ID
                    $d["order_payment_trans_id"] = $transaction->trxn_number();
                    return false;
                    break;
             case "True":
                    $d["order_payment_log"] = $PHPSHOP_LANG->_PHPSHOP_PAYMENT_TRANSACTION_SUCCESS;
                    // Catch Transaction ID
                    $d["order_payment_trans_id"] = $transaction->trxn_number();
                    break;
             default:
                $d["error"] = "True or False not returned for transaction status";
                $d["error"] .= "(".$transaction->trxn_status().")";
                return false;
                break;           
        }
    }
   
}

 /**
 * Electronic Payment XML Interface
 **/
 class electronic_payment {
     var $parser;
     var $xml_data;
     var $current_tag;

     /* Call back Functions for the XML Parser */
     function ep_xml_element_start ($parser, $tag, $attributes) {
         $this->current_tag = $tag; 
     }

     function ep_xml_element_end ($parser, $tag) {
         $this->current_tag = "";
     }

     function ep_xml_data ($parser, $cdata) {
         $this->xml_data[$this->current_tag] = $cdata;
     }


     /* Public Properties */
     function trxn_error () {
         return $this->xml_data['ewayTrxnError'];
     }

     function trxn_status () {
         return $this->xml_data['ewayTrxnStatus'];
     }

     function trxn_number () {
         return $this->xml_data['ewayTrxnNumber'];
     }
    
     function trxn_reference () {
         return $this->xml_data['ewayTrxnReference'];
     }

     /* Instantiating Function */
     function electronic_payment ($my_customerid, $my_totalamount, $my_firstname, $my_lastname,
                                  $my_email, $my_address, $my_postcode, $my_invoice_description,
                                  $my_invoice_ref, $my_card_name, $my_card_number, $my_card_exp_month,
                                  $my_card_exp_year, $cvv_code) {
        global $PHPSHOP_LANG;
         /* PHP currently lacks stable XML DOM functions - instead we build our
            XML request manually. */
        $my_trxn_number = uniqid( "eway_" );
         $xml_request = "
                <ewaygateway>
                    <ewayCustomerID>$my_customerid</ewayCustomerID>
                    <ewayTotalAmount>$my_totalamount</ewayTotalAmount>
                    <ewayCustomerFirstName>$my_firstname</ewayCustomerFirstName>
                    <ewayCustomerLastName>$my_lastname</ewayCustomerLastName>
                    <ewayCustomerEmail>$my_email</ewayCustomerEmail>
                    <ewayCustomerAddress>$my_address</ewayCustomerAddress>
                    <ewayCustomerPostcode>$my_postcode</ewayCustomerPostcode>
                    <ewayCustomerInvoiceDescription>$my_invoice_description</ewayCustomerInvoiceDescription>
                    <ewayCustomerInvoiceRef>$my_invoice_ref</ewayCustomerInvoiceRef>
                    <ewayCardHoldersName>$my_card_name</ewayCardHoldersName>
                    <ewayCardNumber>$my_card_number</ewayCardNumber>
                    <ewayCardExpiryMonth>$my_card_exp_month</ewayCardExpiryMonth>
                    <ewayCardExpiryYear>$my_card_exp_year</ewayCardExpiryYear>
                    <ewayTrxnNumber>$my_trxn_number</ewayTrxnNumber>
                    <ewayOption1>0</ewayOption1>
                    <ewayOption2>0</ewayOption2>
                    <ewayOption3>0</ewayOption3>";
        if( !empty( $cvv_code )) {
            $xml_request .= "
                <ewayCVN >$cvv_code</ewayCVN >";
        }
        $xml_request .= "
                </ewaygateway>
          ";
          
          /* Use CURL to execute XML POST and write output to the temp file */
          $CR = curl_init (GATEWAY_URL);
          
          curl_setopt ($CR, CURLOPT_POST, true);
          curl_setopt ($CR, CURLOPT_POSTFIELDS, $xml_request);
          curl_setopt($CR, CURLOPT_FAILONERROR, true); 
          curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);          
          curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
          
          $xml_response = curl_exec($CR);
          
          $error = curl_error( $CR );
          if( !empty( $error )) {
            echo curl_error( $CR );
            $html = "<br/><span class=\"message\">".$PHPSHOP_LANG->_PHPSHOP_PAYMENT_INTERNAL_ERROR." eway</span>";
            return false;
          }
          else {
              //echo $result; exit();
          }
          curl_close( $CR );

          $this->parser = xml_parser_create();

          /* Disable XML tag capitalisation (Case Folding) */
          xml_parser_set_option ($this->parser, XML_OPTION_CASE_FOLDING, FALSE);

          /* Define Callback functions for XML Parsing */
          xml_set_object($this->parser, $this);
          xml_set_element_handler ($this->parser, "ep_xml_element_start", "ep_xml_element_end");
          xml_set_character_data_handler ($this->parser, "ep_xml_data");

          /* Parse the XML response */
          xml_parse($this->parser, $xml_response, TRUE);
          
          /* Clean up after ourselves */
          xml_parser_free ($this->parser);

     }

 }

?>
