<?php
/*
NETREGISTRY PAYMENT MODULE FOR osCOMMERCE 2.2 MS2
------------------------------------------------
Version 1.0 - for osCommerce 2.2 MS2
Copyright (c) 2005 Attitude Group Ltd
Released under the GNU General Public License
http://www.oscommerce.co.nz/contributions/netregistry01.zip

by Geoff Ford - Attitude Group Ltd - 1 June 2005
Contact Details available on website
http://www.oscommerce.co.nz/

NetRegistry Payment Module for osCommerce 2.2 MS2 is released under 
the terms of the General Public License. Please see the license.txt 
for more details.

Credits
-------
NetRegistry have paid for development of this module.

NetRegistry http://www.netregistry.com.au
Tel:      +61 2 9699 6099  I Fax:  +61 2 9699 6088
PO Box 270 Broadway NSW 2007 Australia
*/

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();



  class netregistry {
    var $code, $title, $description, $enabled;

// class constructor
    function netregistry() {
      global $order;

      $this->code = 'netregistry';
      $this->enabled = ((MODULE_PAYMENT_NETREGISTRY_STATUS == 'True') ? true : false);
      $this->sort_order = MODULE_PAYMENT_NETREGISTRY_SORT_ORDER;
	  $name = "Net Registry";
	  if(defined('MODULE_PAYMENT_CASH_IMAGE')) $image = MODULE_PAYMENT_NETREGISTRY_IMAGE;	  
	  	if($image != "" && file_exists($path . DIR_WS_IMAGES . $image)){			
			$image = '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" width="103" height="33">';			
		}else{
			$image_array = array('.gif','.jpg','.jpeg','.png');
			$image_check = true;
			for($i=0;$i<sizeof($image_array);$i++){
				if($image_check && $image != "" && file_exists($path . DIR_WS_IMAGES . $image . $image_array[$i])){
					$image = '<img src="'. HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . $image_array[$i] . '" width="103" height="33">';
					$image_check = false;
				}
			}
			if($image_check)$image = "";
		}
	   define('MODULE_PAYMENT_NETREGISTRY_TEXT_TITLE', $name .'&nbsp;&nbsp;'. $image);	   
	   define('MODULE_PAYMENT_NETREGISTRY_TEXT_TEXT_TITLE', $name);
	   $this->title = (defined('MODULE_PAYMENT_NETREGISTRY_TEXT_TITLE') ? MODULE_PAYMENT_NETREGISTRY_TEXT_TITLE : 'Net Registry'); // Change this for changing what appears on your site	   
	   $this->text_title=MODULE_PAYMENT_NETREGISTRY_TEXT_TEXT_TITLE;
	   $this->description = (defined('MODULE_PAYMENT_NETREGISTRY_TEXT_DESCRIPTION') ? MODULE_PAYMENT_NETREGISTRY_TEXT_DESCRIPTION : 'NetRegistry Payment Module');
		
      if ((int)MODULE_PAYMENT_NETREGISTRY_ORDER_STATUS_ID > 0) {
        $this->order_status = MODULE_PAYMENT_NETREGISTRY_ORDER_STATUS_ID;
      }
      if (is_object($order)) $this->update_status();

      $this->netregistry_url = 'https://4tknox.au.com/cgi-bin/themerchant.au.com/ecom/external2.pl';
    }

    
// class methods
    function update_status() {
      global $order;

      if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_NETREGISTRY_ZONE > 0) ) {
        $check_flag = false;
        $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_NETREGISTRY_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }

        if ($check_flag == false) {
          $this->enabled = false;
        }
      }
    }

    function javascript_validation() {
      $js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
            '    var cc_owner = document.checkout_payment.netregistry_cc_owner.value;' . "\n" .
            '    var cc_number = document.checkout_payment.netregistry_cc_number.value;' . "\n" .
            '    if (cc_owner == "" || cc_owner.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_NETREGISTRY_TEXT_JS_CC_OWNER . '";' . "\n" .
            '      error = 1;' . "\n" .
            '    }' . "\n" .
            '    if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_NETREGISTRY_TEXT_JS_CC_NUMBER . '";' . "\n" .
            '      error = 1;' . "\n" .
            '    }' . "\n" .
            '  }' . "\n";

      return $js;
    }

    function selection() {
      global $order;

      for ($i=1; $i<13; $i++) {
        $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B',mktime(0,0,0,$i,1,2000)));
      }

      $today = getdate(); 
      for ($i=$today['year']; $i < $today['year']+10; $i++) {
        $expires_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
      }
      $selection = array('id' => $this->code,
                         'module' => $this->title,
                         'fields' => array(array('title' => '',
                                                 'field' => MODULE_PAYMENT_NETREGISTRY_SUPPORTED_CARDS),
                         		   array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_OWNER,
                                                 'field' => tep_draw_input_field('netregistry_cc_owner', $order->billing['firstname'] . ' ' . $order->billing['lastname'])),
                                           array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_NUMBER,
                                                 'field' => tep_draw_input_field('netregistry_cc_number')),
                                           array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_EXPIRES,
                                                 'field' => tep_draw_pull_down_menu('netregistry_cc_expires_month', $expires_month) . '&nbsp;' . tep_draw_pull_down_menu('netregistry_cc_expires_year', $expires_year))));

      return $selection;
    }

    function pre_confirmation_check() {
      global $HTTP_POST_VARS;

      include(DIR_WS_CLASSES . 'cc_validation.php');

      $cc_validation = new cc_validation();
      $result = $cc_validation->validate($HTTP_POST_VARS['netregistry_cc_number'], $HTTP_POST_VARS['netregistry_cc_expires_month'], $HTTP_POST_VARS['netregistry_cc_expires_year']);
      $error = '';
      switch ($result) {
        case -1:
          $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
          break;
        case -2:
        case -3:
        case -4:
          $error = TEXT_CCVAL_ERROR_INVALID_DATE;
          break;
        case false:
          $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
          break;
      }

      if ( ($result == false) || ($result < 1) ) {
        $payment_error_return = 'payment_error=' . $this->code . '&error=' . urlencode($error) . '&netregistry_cc_owner=' . urlencode($HTTP_POST_VARS['netregistry_cc_owner']) . '&netregistry_cc_expires_month=' . $HTTP_POST_VARS['netregistry_cc_expires_month'] . '&netregistry_cc_expires_year=' . $HTTP_POST_VARS['netregistry_cc_expires_year'];

        tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
      }

      $this->cc_card_type = $cc_validation->cc_type;
      $this->cc_card_number = $cc_validation->cc_number;
      $this->cc_expiry_month = $cc_validation->cc_expiry_month;
      $this->cc_expiry_year = $cc_validation->cc_expiry_year;
    }

    function confirmation() {
      global $HTTP_POST_VARS;

      $confirmation = array('title' => $this->title . ': ' . $this->cc_card_type,
                            'fields' => array(array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_OWNER,
                                                    'field' => $HTTP_POST_VARS['netregistry_cc_owner']),
                                              array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_NUMBER,
                                                    'field' => substr($this->cc_card_number, 0, 4) . str_repeat('X', (strlen($this->cc_card_number) - 8)) . substr($this->cc_card_number, -4)),
                                              array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_CREDIT_CARD_EXPIRES,
                                                    'field' => strftime('%B, %Y', mktime(0,0,0,$HTTP_POST_VARS['netregistry_cc_expires_month'], 1, '20' . $HTTP_POST_VARS['netregistry_cc_expires_year'])))));

      return $confirmation;
    }

    function process_button() {
      global $HTTP_SERVER_VARS, $HTTP_POST_VARS, $order, $customer_id;

      //register session var to check against total - avoid direct posting to checkout_process.php
      $GLOBALS['ft_validation'] = md5($order->info['total'].$this->cc_card_number.$this->cc_expiry_month . '/' .  substr($this->cc_expiry_year, -2).MODULE_PAYMENT_NETREGISTRY_USERNAME.MODULE_PAYMENT_NETREGISTRY_PASSWORD);
      tep_session_register('ft_validation');

      $process_button_string = tep_draw_hidden_field('ft', $order->info['total']) .
      			       tep_draw_hidden_field('cc_owner', $HTTP_POST_VARS['netregistry_cc_owner']) .
                               tep_draw_hidden_field('cc_expires', $this->cc_expiry_month . '/' .  substr($this->cc_expiry_year, -2)) .
                               tep_draw_hidden_field('cc_type', $this->cc_card_type) .
                               tep_draw_hidden_field('cc_number', $this->cc_card_number);

      return $process_button_string;
    }

    function before_process() {
      global $HTTP_POST_VARS,$customer_id, $order, $ft_validation;
	//validate amount and other clean data from confirmation page (prevent anyone direct posting to checkout_process.php)
	//workaround issue with order total modules in checkout_process.php
	if (is_numeric($HTTP_POST_VARS['ft']) && ($ft_validation == md5($HTTP_POST_VARS['ft'].$HTTP_POST_VARS['cc_number'].$HTTP_POST_VARS['cc_expires'].MODULE_PAYMENT_NETREGISTRY_USERNAME.MODULE_PAYMENT_NETREGISTRY_PASSWORD))) 
		$amount = round($HTTP_POST_VARS['ft']);
	else 
		tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode(MODULE_PAYMENT_NETREGISTRY_TEXT_BADPOST_MESSAGE), 'SSL', true, false));	
	
	//construct query ...
	$params = 'COMMAND='.MODULE_PAYMENT_NETREGISTRY_METHOD;
	$params .= '&LOGIN=';
	$params .= MODULE_PAYMENT_NETREGISTRY_USERNAME.'/'.MODULE_PAYMENT_NETREGISTRY_PASSWORD;
	$params .= '&AMOUNT=';
	$params .= number_format($amount, 2, '.','');
	$params .= '&CCNUM=';
	$params .= $HTTP_POST_VARS['cc_number'];
	$params .= '&CCEXP=';
	$params .= $HTTP_POST_VARS['cc_expires'];
	$params .= '&COMMENT=';
	$params .= $customer_id."-".date("YmdHis");

 	//time to send ...
        $curl = curl_init();
        //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt($curl, CURLOPT_URL, $this->netregistry_url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_POSTFIELDSIZE, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //curl_setopt($curl, CURLOPT_SSLVERSION, 0.9.7);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,  2);
    
	$netregistry_success = false;
	
    if ($result = curl_exec($curl)) {
    	$netregistry_result = explode("\n", $result);
	  	if (strtolower($netregistry_result[0]) == 'approved') $netregistry_success = true;	  	
    }


       if (MODULE_PAYMENT_NETREGISTRY_DEBUG == 'On') {
          echo '<pre>';
          echo 'DEBUG INFORMATION:'."\n\n";
          echo 'Parameters sent to NetRegistry: '.$params."\n\n";
          echo 'Status of transaction: '.$netregistry_result[0]."\n\n";
          echo 'Full response from NetRegistry: '.$result."\n\n";
          echo 'CURL error number: '.curl_errno($curl)."\n\n";
          echo 'CURL error message: '.curl_error($curl)."\n\n";
          echo 'CURL information: '.print_r(curl_getinfo($curl),TRUE)."\n\n";
          echo '</pre>';
         $netregistry_error_redirect=curl_error($curl);
      }
        
        curl_close($curl);
/*$host = '4tknox.au.com'; // domain only, no path info
$path = '/cgi-bin/themerchant.au.com/ecom/external2.pl'; // path to cgi, asp, php program


$fp = @fsockopen ("ssl://$host", 443, $errno, $errstr, 50);
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($params) . "\r\n");

fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $params);

while (!feof($fp)) {
	$data .= fgets($fp,128);
}
fclose($fp);
print_r($data);*/
				// (OPTIONALLY strip header returned (for XML response only), use $data otherwise
				//ereg("<(.+)",$data,$matched);
				//$vpcResponse = $matched[1];
				$vpcResponse = $data;

        if (!$netregistry_success) {
          tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . (($netregistry_error_redirect)?urlencode($netregistry_error_redirect):'Netregistry information missing'), 'SSL', true, false));
        }
        
        $order->info['cc_number'] =  str_repeat('X', (strlen($HTTP_POST_VARS['cc_number']) - 4)) . substr($HTTP_POST_VARS['cc_number'], -4);
	
    }

    function after_process() {
      return false;
    }

    function get_error() {
      global $HTTP_GET_VARS;

      $error = array('title' => MODULE_PAYMENT_NETREGISTRY_TEXT_ERROR,
                     'error' => stripslashes(urldecode($HTTP_GET_VARS['error'])));

      return $error;
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_NETREGISTRY_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function install() {
    	
      //verify that have curl and warn if no curl (curl_version)
      if (!extension_loaded('curl')) {
        global $messageStack;
      	$messageStack->add_session('No CURL installed with PHP. This is required for the NetRegistry module. Contact your host/developer about installing this.', 'warning');
      }
      
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable NetRegistry Module', 'MODULE_PAYMENT_NETREGISTRY_STATUS', 'True', 'Do you want to accept NetRegistry payments?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('NetRegistry Merchant ID', 'MODULE_PAYMENT_NETREGISTRY_USERNAME', '', 'The Merchant ID used for the NetRegistry service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('NetRegistry Password', 'MODULE_PAYMENT_NETREGISTRY_PASSWORD', '', 'The External Password used for the NetRegistry service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Method', 'MODULE_PAYMENT_NETREGISTRY_METHOD', 'Test', 'Transaction method used for processing orders', '6', '0', 'tep_cfg_select_option(array(\'Test\', \'Production\'), ', now())");      
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Debug Mode', 'MODULE_PAYMENT_NETREGISTRY_DEBUG', 'Off', 'Use this only for debugging problems - setting to On will show debug output. Off should be used in all production environments.', '6', '0', 'tep_cfg_select_option(array(\'Off\', \'On\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_NETREGISTRY_SORT_ORDER', '1', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_NETREGISTRY_ZONE', '3', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_NETREGISTRY_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Display Name', 'MODULE_PAYMENT_NETREGISTRY_DISPLAY_NAME', 'Net Registry', 'Set the Display name to payment module', '6', '12', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Image', 'MODULE_PAYMENT_NETREGISTRY_IMAGE', 'netregistry', 'Set the Image of payment module', '6', '13', 'tep_cfg_file_field(', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Net Registry - Exclude these Countries', 'MODULE_PAYMENT_NETREGISTRY_EXCEPT_COUNTRY', '', 'Net Registry - If countries are selected, disable this payment method for that countries.', '6', '9', 'tep_cfg_pull_down_zone_except_countries(MODULE_PAYMENT_NETREGISTRY_ZONE,', 'tep_get_zone_except_country', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Net Registry - Exclude these Zones', 'MODULE_PAYMENT_NETREGISTRY_EXCEPT_ZONE', '2', 'Net Registry - If a zone is selected, disable this payment method for that zone.', '6', '10', 'tep_cfg_pull_down_zone_classes(','tep_get_zone_class_title', now())");


    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      return array('MODULE_PAYMENT_NETREGISTRY_STATUS', 
	  			   'MODULE_PAYMENT_NETREGISTRY_USERNAME', 
				   'MODULE_PAYMENT_NETREGISTRY_PASSWORD', 
				   'MODULE_PAYMENT_NETREGISTRY_METHOD',
				   'MODULE_PAYMENT_NETREGISTRY_DEBUG',
				   'MODULE_PAYMENT_NETREGISTRY_ZONE', 
				   'MODULE_PAYMENT_NETREGISTRY_ORDER_STATUS_ID', 
				   'MODULE_PAYMENT_NETREGISTRY_SORT_ORDER',
				   'MODULE_PAYMENT_NETREGISTRY_DISPLAY_NAME',
				   'MODULE_PAYMENT_NETREGISTRY_IMAGE',
				   'MODULE_PAYMENT_NETREGISTRY_EXCEPT_COUNTRY',
				   'MODULE_PAYMENT_NETREGISTRY_EXCEPT_ZONE');
    }
  }
  
?>