<?php
/*

  osCommRes, Services Oline 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare 

Released under the GNU General Public License 
*/

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


  class westpac {
    var $code, $title, $description, $enabled, $states,$fingerprint;

// class constructor
	function westpac() {
		
		global $order;
		$this->code ='westpac';
		$name = "WestPac Payment";
		$image = "";
		if(MODULE_PAYMENT_WESTPAC_DISPLAY_NAME != "MODULE_PAYMENT_WESTPAC_DISPLAY_NAME")$name = MODULE_PAYMENT_WESTPAC_DISPLAY_NAME;
		if(MODULE_PAYMENT_WESTPAC_IMAGE != "MODULE_PAYMENT_WESTPAC_IMAGE")$image = MODULE_PAYMENT_WESTPAC_IMAGE;
		if(DIR_WS_ADMIN != "DIR_WS_ADMIN" && DIR_WS_ADMIN != "")$path = "../";
		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_WESTPAC_TEXT_TITLE', $name . '&nbsp;&nbsp;' . $image);
		define('MODULE_PAYMENT_WESTPAC_TEXT_TEXT_TITLE', $name);
		$this->title = MODULE_PAYMENT_WESTPAC_TEXT_TITLE;
		$this->text_title = MODULE_PAYMENT_WESTPAC_TEXT_TEXT_TITLE;
		$this->description = MODULE_PAYMENT_WESTPAC_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_PAYMENT_WESTPAC_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_WESTPAC_STATUS == 'True') ? true : false);
		$this->barred=false;
		if ((int)MODULE_PAYMENT_WESTPAC_ORDER_STATUS_ID > 0) {
			$this->order_status = MODULE_PAYMENT_WESTPAC_ORDER_STATUS_ID;
		}
		
		if (is_object($order)) $this->update_status();
		$this->form_action_url = ((MODULE_PAYMENT_WESTPAC_TESTMODE == 'Test') ? "https://verifytransact.webadvantage.com.au/3dsecure/verifyEnrollment.jsp" : "https://transact.webadvantage.com.au/3dsecure/verifyEnrollment.jsp");
	}

// class methods
    function update_status() {
      global $order;
	  
	  tep_check_module_status($this,MODULE_PAYMENT_WESTPAC_ZONE,trim(MODULE_PAYMENT_WESTPAC_EXCEPT_ZONE),trim(MODULE_PAYMENT_WESTPAC_EXCEPT_COUNTRY));
  	  $this->barred=tep_check_payment_barred(trim(MODULE_PAYMENT_WESTPAC_EXCEPT_COUNTRY));
    }

    function javascript_validation() {
      $js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
            '    var cc_owner = document.checkout_payment.westpac_cc_owner.value;' . "\n" .
            '    var cc_number = document.checkout_payment.westpac_cc_number.value;' . "\n" .
            '    if (cc_owner == "" || cc_owner.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_WESTPAC_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_WESTPAC_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' => sprintf('%02d', $i)); //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,
						 'barred'=>$this->barred,
                         'fields' => array(array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_OWNER,
                                                 'field' => tep_draw_input_field('westpac_cc_owner', $order->billing['firstname'] . ' ' . $order->billing['lastname'])),
                                           array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_NUMBER,
                                                 'field' => tep_draw_input_field('westpac_cc_number')),
										   array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_CVV,
										   		 'field' => tep_draw_input_field('westpac_cvv', '', 'size=3 maxlength=3')),
                                           array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_EXPIRES,
                                                 'field' => tep_draw_pull_down_menu('westpac_cc_expires_month', $expires_month) . '&nbsp;' . tep_draw_pull_down_menu('westpac_cc_expires_year', $expires_year
										   		))));

      return $selection;
    }

    function pre_confirmation_check() {
      global $HTTP_POST_VARS,$order,$referenceID,$finger_print;

      include(DIR_WS_CLASSES . 'cc_validation.php');

      $cc_validation = new cc_validation();
      $result = $cc_validation->validate($HTTP_POST_VARS['westpac_cc_number'], $HTTP_POST_VARS['westpac_cc_expires_month'], $HTTP_POST_VARS['westpac_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) . '&westpac_cc_owner=' . urlencode($HTTP_POST_VARS['westpac_cc_owner']) . '&westpac_cc_type=' . urlencode($HTTP_POST_VARS['westpac_cc_type']) . '&westpac_cc_expires_month=' . $HTTP_POST_VARS['westpac_cc_expires_month'] . '&westpac_cc_expires_year=' . $HTTP_POST_VARS['westpac_cc_expires_year'];
			tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
      }
      $this->cc_card_owner = $HTTP_POST_VARS['westpac_cc_owner']; 
      $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;
      $this->cc_cvv = $HTTP_POST_VARS['westpac_cvv'];
	  $this->cc_type=$cc_validation->cc_type;
    }

    function confirmation() {
      global $HTTP_POST_VARS;

      $confirmation = array('title' => $this->title,
                            'fields' => array(array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_OWNER,
                                                    'field' => $HTTP_POST_VARS['westpac_cc_owner']),
                                              array('title' => MODULE_PAYMENT_WESTPAC_TEXT_TYPE,
                                                    'field' => $HTTP_POST_VARS['westpac_cc_type']),
                                              array('title' => MODULE_PAYMENT_WESTPAC_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_WESTPAC_TEXT_CREDIT_CARD_EXPIRES,
                                                    'field' => strftime('%B, %Y', mktime(0,0,0,$HTTP_POST_VARS['westpac_cc_expires_month'], 1, '20' . $HTTP_POST_VARS['westpac_cc_expires_year']))),
											  array('title' => MODULE_PAYMENT_WESTPAC_TEXT_CREDIT_CARD_CVV,
											  		'field' => $HTTP_POST_VARS['westpac_cvv'])));

      return $confirmation;
    }

    function process_button() {
      global $HTTP_SERVER_VARS, $order, $referenceID,$validID,$payment_page,$_SERVER;
	    $cur_time=date('YmdHis',getGMTTime());
		
		//$referenceID="satsat6789012345";
	    $finger_url=((MODULE_PAYMENT_WESTPAC_TESTMODE == 'Test') ?"https://verifytransact.webadvantage.com.au/post/genfingerprint":"https://transact.webadvantage.com.au/post/genfingerprint");
		$req=sprintf("EPS_MERCHANT=%s&EPS_PASSWORD=%s&EPS_AMOUNT=%s&EPS_REFERENCEID=%s&EPS_TIMESTAMP=%s",MODULE_PAYMENT_WESTPAC_MERCHANT_ID,
						MODULE_PAYMENT_WESTPAC_PASSWORD,number_format($order->info["total"],2,'.',''),$referenceID,$cur_time
						);
						
						//echo $req;
		$response="";
		$response=@file_get_contents($finger_url . "?" .$req);

		$response=str_replace(chr(13). chr(10),"",$response);
		$response=trim($response);
		//echo $response;
		//echo 'This is response'.$response;
		
		//$response="MCwCFGMinjZ9jAetJZE9N4YrCr2r15gIAhRTmfiP4xMkpOndDWYWg+ZKJ+C2sg";

		$return_link=tep_href_link(FILENAME_CHECKOUT_WESTPAC_RESULT, '', 'SSL');
		
		//echo $return_link;
		if (strpos($return_link,tep_session_name())===false)
			$return_link.="?" . tep_session_name() . "=" . tep_session_id();
			
      $process_button_string = tep_draw_hidden_field('EPS_TIMESTAMP', $cur_time) .
                               tep_draw_hidden_field('EPS_AMOUNT', number_format($order->info['total'],2,'.','')) .
	  						   tep_draw_hidden_field('EPS_MERCHANT', MODULE_PAYMENT_WESTPAC_MERCHANT_ID) .
   							   tep_draw_hidden_field('EPS_PASSWORD', MODULE_PAYMENT_WESTPAC_PASSWORD) .
							   tep_draw_hidden_field('EPS_REFERENCEID', $referenceID) .
							   tep_draw_hidden_field('EPS_FINGERPRINT', $response) .
                         	   tep_draw_hidden_field('EPS_CARDNUMBER', $this->cc_card_number) .
                               tep_draw_hidden_field('EPS_EXPIRYMONTH', $this->cc_expiry_month) .
							   tep_draw_hidden_field('EPS_CARDTYPE', strtolower(str_replace(" ","",$this->cc_type))) .
							   tep_draw_hidden_field('EPS_CCV', $this->cc_cvv) .
                               tep_draw_hidden_field('EPS_EXPIRYYEAR', substr($this->cc_expiry_year, -2)) .
							   tep_draw_hidden_field('EPS_TXNTYPE','ANTIFRAUD') .
							   tep_draw_hidden_field('EPS_3DSECURE',"true") .
							   tep_draw_hidden_field('3D_XID',sprintf("%-020s","UP" .date('YmdHis',getGMTTime()))) .
							   tep_draw_hidden_field('EPS_MERCHANTNUM',MODULE_PAYMENT_WESTPAC_MERCHANT_NUMBER) .
							   tep_draw_hidden_field('EPS_IP',$_SERVER['REMOTE_ADDR']) .
							   /*tep_draw_hidden_field('EPS_FIRSTNAME',$order->customer['firstname']) . 
							   tep_draw_hidden_field('EPS_LASTNAME',$order->customer['lastname']) . 
							   tep_draw_hidden_field('EPS_ZIPCODE',$order->customer['zipcode']) . 
							   tep_draw_hidden_field('EPS_TOWN',$order->customer['city']) .
							   tep_draw_hidden_field('EPS_BILLINGCOUNTRY',$order->billing['country']['iso_code_2']) . 
							   tep_draw_hidden_field('EPS_DELIVERYCOUNTRY',$order->delivery['country']['iso_code_2']) . 
							   tep_draw_hidden_field('EPS_EMAILADDRESS',$order->customer['email_address']) .*/

                               "<input type='hidden' name='EPS_RESULTURL' value='" . $return_link . "'>";

      //$process_button_string .= tep_draw_hidden_field(tep_session_name(), tep_session_id());

      return $process_button_string;
    }

    function before_process() {
      return false;
    }

    function after_process() {
      return false;
    }

    function get_error() {
      global $HTTP_GET_VARS;

      $msg = "";
      if (stripslashes(urldecode($HTTP_GET_VARS['response_text'])) != "")
        $msg = stripslashes(urldecode($HTTP_GET_VARS['response_text']));
      else if (stripslashes(urldecode($HTTP_GET_VARS['error'])) != "")
        $msg = stripslashes(urldecode($HTTP_GET_VARS['error']));
      $error = array('title' => MODULE_PAYMENT_WESTPAC_TEXT_ERROR,
                     'error' => $msg);

      return $error;
    }

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

    function install() {
      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 WestPac Module', 'MODULE_PAYMENT_WESTPAC_STATUS', 'True', 'Do you want to accept WestPac payments?', '6', '1', '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, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_WESTPAC_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 ('Exclude these Countries', 'MODULE_PAYMENT_WESTPAC_EXCEPT_COUNTRY', '', 'If countries are selected, disable this payment method for that countries.', '6', '3', 'tep_cfg_pull_down_zone_except_countries(MODULE_PAYMENT_WESTPAC_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 ('Exclude these Zones', 'MODULE_PAYMENT_WESTPAC_EXCEPT_ZONE', '', 'If a zone is selected, disable this payment method for that zone.', '6', '4', 'tep_cfg_pull_down_zone_classes(','tep_get_zone_class_title', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Merchant ID', 'MODULE_PAYMENT_WESTPAC_MERCHANT_ID', 'sec0001', 'The merchant id used for the WestPac service', '6', '5', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Merchant Number', 'MODULE_PAYMENT_WESTPAC_MERCHANT_NUMBER', 'WMer001', 'The merchant number used for the WestPac service', '6', '6', 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 Mode', 'MODULE_PAYMENT_WESTPAC_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '7', '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, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_WESTPAC_SORT_ORDER', '16', 'Sort order of display. Lowest is displayed first.', '6', '8', 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_WESTPAC_ORDER_STATUS_ID', '16', 'Set the status of orders made with this payment module to this value', '6', '9', '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, set_function, use_function, date_added) values ('Password', 'MODULE_PAYMENT_WESTPAC_PASSWORD', '0', 'The password is used for the WestPac service', '6', '10', '', '', 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_WESTPAC_DISPLAY_NAME', 'WestPac Payment', 'Set the Display name to payment module', '6', '11', 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_WESTPAC_IMAGE', 'westpac', 'Set the Image of payment module', '6', '12', 'tep_cfg_file_field(', now())");
    }

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

    function keys() {
      return array('MODULE_PAYMENT_WESTPAC_STATUS', 'MODULE_PAYMENT_WESTPAC_ZONE',  'MODULE_PAYMENT_WESTPAC_EXCEPT_ZONE', 'MODULE_PAYMENT_WESTPAC_EXCEPT_COUNTRY', 'MODULE_PAYMENT_WESTPAC_MERCHANT_ID', 'MODULE_PAYMENT_WESTPAC_MERCHANT_NUMBER', 'MODULE_PAYMENT_WESTPAC_TESTMODE', 'MODULE_PAYMENT_WESTPAC_SORT_ORDER', 'MODULE_PAYMENT_WESTPAC_ORDER_STATUS_ID','MODULE_PAYMENT_WESTPAC_PASSWORD','MODULE_PAYMENT_WESTPAC_MERCHANT_NUMBER','MODULE_PAYMENT_WESTPAC_DISPLAY_NAME','MODULE_PAYMENT_WESTPAC_IMAGE');
    }
  }
  

?>