<?php
/*
  $Id: cc.php,v 1.53 2003/02/04 09:55:01 project3000 Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
  class cybersource {
    var $code, $title, $description, $enabled;

// class constructor
	function cybersource() {
		global $order,$image;
		
		$this->code = 'cybersource';
		$name = "Cybersource Payment";
		$image = "";
		if(MODULE_PAYMENT_CYBS_DISPLAY_NAME != "MODULE_PAYMENT_CYBS_DISPLAY_NAME")$name = MODULE_PAYMENT_CYBS_DISPLAY_NAME;
		if(MODULE_PAYMENT_CYBS_IMAGE != "MODULE_PAYMENT_CYBS_IMAGE")$image = MODULE_PAYMENT_CYBS_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_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_CATALOG . DIR_WS_IMAGES . $image . $image_array[$i] . '" width="103" height="33">';
					$image_check = false;
				}
			}
			if($image_check)$image = "";
		}
		define('SS_MODULE_PAYMENT_CYBS_TEXT_TITLE', $name . '&nbsp;&nbsp;' . $image);
		define('MODULE_PAYMENT_CYBS_TEXT_TEXT_TITLE', $name);
		$this->title = SS_MODULE_PAYMENT_CYBS_TEXT_TITLE;
		$this->text_title = MODULE_PAYMENT_CYBS_TEXT_TEXT_TITLE;
		$this->description = MODULE_PAYMENT_CYBS_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_PAYMENT_CYBS_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_CYBS_STATUS == 'True') ? true : false);
		
		if ($this->enabled) $this->enabled=((cybs_loaded()=='True')?true:false);
		
		if ((int)MODULE_PAYMENT_CYBS_ORDER_STATUS_ID > 0) {
			$this->order_status = MODULE_PAYMENT_CYBS_ORDER_STATUS_ID;
		}
		
		if (is_object($order)) $this->update_status();
		
	}

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

      if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_CYBS_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_CYBS_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 billTo_firstName = document.checkout_payment.billTo_firstName.value;' . "\n" .
            '    var billTo_lastName = document.checkout_payment.billTo_lastName.value;' . "\n" .
            '    var card_accountNumber = document.checkout_payment.card_accountNumber.value;' . "\n" .
            '    if (billTo_firstName == "" || billTo_firstName.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_CYBS_TEXT_JS_CYBS_FIRST_NAME . '";' . "\n" .
            '      error = 1;' . "\n" .
            '    }' . "\n" .
            '    if (billTo_lastName == "" || billTo_lastName.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_CYBS_TEXT_JS_CYBS_LAST_NAME . '";' . "\n" .
            '      error = 1;' . "\n" .
            '    }' . "\n" .
            '    if (card_accountNumber == "" || card_accountNumber.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
            '      error_message = error_message + "' . MODULE_PAYMENT_CYBS_TEXT_JS_CYBS_NUMBER . '";' . "\n" .
            '      error = 1;' . "\n" .
            '    }' . "\n" .
            '  }' . "\n";

      return $js;
    }

    function selection() {
      global $order,$image;

      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)));
      }

      $types = array('Visa','MasterCard','American Express','Discover','Diners Club','JCB');
	  for($i = 0; $i < sizeof($types); $i++) {
	    if( bitmap_value($i) )
          $card_types[] = array('id' => '00' . ($i + 1), 'text' => $types[$i]);
      }

	  if (MODULE_PAYMENT_CYBS_CVV == 'Disabled') {
        $selection = array('id' => $this->code,
                         'module' => 'Credit Card&nbsp;&nbsp;' . $image,
                         'fields' => array(array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_TYPE,
                                                 'field' => tep_draw_pull_down_menu('card_cardType', $card_types)),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_FIRST_NAME,
                                                 'field' => tep_draw_input_field('billTo_firstName', $order->billing['firstname'])),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_LAST_NAME,
                                                 'field' => tep_draw_input_field('billTo_lastName', $order->billing['lastname'])),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_NUMBER,
                                                 'field' => tep_draw_input_field('card_accountNumber')),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_EXPIRES,
                                                 'field' => tep_draw_pull_down_menu('card_expirationMonth', $expires_month) . '&nbsp;' . tep_draw_pull_down_menu('card_expirationYear', $expires_year))));
	  } else {
        $selection = array('id' => $this->code,
                         'module' => 'Credit Card&nbsp;&nbsp;' . $image,
                         'fields' => array(array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_TYPE,
                                                 'field' => tep_draw_pull_down_menu('card_cardType', $card_types)),
                         				   array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_FIRST_NAME,
                                                 'field' => tep_draw_input_field('billTo_firstName', $order->billing['firstname'])),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_LAST_NAME,
                                                 'field' => tep_draw_input_field('billTo_lastName', $order->billing['lastname'])),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_NUMBER,
                                                 'field' => tep_draw_input_field('card_accountNumber')),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_CVV_NUMBER,
                                                 'field' => tep_draw_input_field('card_cvNumber')),
                                           array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_EXPIRES,
                                                 'field' => tep_draw_pull_down_menu('card_expirationMonth', $expires_month) . '&nbsp;' . tep_draw_pull_down_menu('card_expirationYear', $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['card_accountNumber'], $HTTP_POST_VARS['card_expirationMonth'], substr($HTTP_POST_VARS['card_expirationYear'], 2, 4));

      switch($cc_validation->cc_type) {
      	case 'Visa':
    		$this->cc_card_type_id = '001';
      		break;
      	case 'Master Card':
      		$this->cc_card_type_id = '002';
      		break;
      	case 'American Express':
      		$this->cc_card_type_id = '003';
      		break;
      	case 'Discover':
      		$this->cc_card_type_id = '004';
      		break;
      	case 'Diners Club':
      		$this->cc_card_type_id = '005';
      		break;
      	case 'JCB':
      		$this->cc_card_type_id = '006';
      		break;
      }

	  if ($HTTP_POST_VARS['card_cardType'] != $this->cc_card_type_id)
	    $result = -5;

	  if(MODULE_PAYMENT_CYBS_CVV == 'Required' && strlen($HTTP_POST_VARS['card_cvNumber']) < 3 || strlen($HTTP_POST_VARS['card_cvNumber']) > 4)
	    $result = -6;
	  if(MODULE_PAYMENT_CYBS_CVV == 'Required' && !$HTTP_POST_VARS['card_cvNumber'])
	    $result = -7;

      $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 -5:
          $error = TEXT_CCVAL_ERROR_CARD_TYPE_MISMATCH;
          break;
        case -6:
          $error = TEXT_CCVAL_ERROR_CARD_CVV_INVALID;
          break;
        case -7:
          $error = TEXT_CCVAL_ERROR_CARD_CVV_MISSING;
          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) . '&billTo_firstName=' . urlencode($HTTP_POST_VARS['billTo_firstName']) . '&billTo_lastName=' . urlencode($HTTP_POST_VARS['billTo_lastName']) . '&card_expirationMonth=' . $HTTP_POST_VARS['card_expirationMonth'] . '&card_expirationYear=' . $HTTP_POST_VARS['card_expirationYear'];
        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;

	  if (MODULE_PAYMENT_CYBS_CVV == 'Disabled') {
        $confirmation = array('title' => 'Credit Card Information: ',
                            'fields' => array(array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_TYPE,
                                                    'field' => $this->cc_card_type),
                                              array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_FIRST_NAME,
                                                    'field' => $HTTP_POST_VARS['billTo_firstName']),
                                              array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_LAST_NAME,
                                                    'field' => $HTTP_POST_VARS['billTo_lastName']),
                                              array('title' => MODULE_PAYMENT_CYBS_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_CYBS_TEXT_CREDIT_CARD_EXPIRES,
                                                    'field' => strftime('%B, %Y', mktime(0,0,0,$HTTP_POST_VARS['card_expirationMonth'], 1, '20' . substr($HTTP_POST_VARS['card_expirationYear'], 2, 4))))));
	  } else {
        $confirmation = array('title' => 'Credit Card Information:',
                            'fields' => array(array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_TYPE,
                                                    'field' => $this->cc_card_type),
                                              array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_FIRST_NAME,
                                                    'field' => $HTTP_POST_VARS['billTo_firstName']),
                                              array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_LAST_NAME,
                                                    'field' => $HTTP_POST_VARS['billTo_lastName']),
                                              array('title' => MODULE_PAYMENT_CYBS_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_CYBS_TEXT_CREDIT_CARD_CVV_NUMBER,
                                                    'field' => $HTTP_POST_VARS['card_cvNumber']),
                                              array('title' => MODULE_PAYMENT_CYBS_TEXT_CREDIT_CARD_EXPIRES,
                                                    'field' => strftime('%B, %Y', mktime(0,0,0,$HTTP_POST_VARS['card_expirationMonth'], 1, '20' . substr($HTTP_POST_VARS['card_expirationYear'], 2, 4))))));
	  }

      return $confirmation;
    }

    function process_button() {
      global $HTTP_POST_VARS, $order, $customer_id,$referenceID;
      $process_button_string = tep_draw_hidden_field('purchaseTotals_grandTotalAmount',$order->info['total']) . "\n" . 
	  						   tep_draw_hidden_field('purchaseTotals_currency',$order->info['currency']) . "\n" .
      						   tep_draw_hidden_field('billTo_company', $order->billing['company']) . "\n" .
      						   tep_draw_hidden_field('billTo_firstName', $HTTP_POST_VARS['billTo_firstName']) . "\n" .
      						   tep_draw_hidden_field('billTo_lastName', $HTTP_POST_VARS['billTo_lastName']) . "\n" .
                               tep_draw_hidden_field('billTo_street1', $order->billing['street_address']) . "\n" .
                               tep_draw_hidden_field('billTo_street2', $order->billing['suburb']) . "\n" .
                               tep_draw_hidden_field('billTo_city', $order->billing['city']) . "\n" .
                               tep_draw_hidden_field('billTo_state', $order->billing['state']) . "\n" .
                               tep_draw_hidden_field('billTo_postalCode', $order->billing['postcode']) . "\n" .
                               tep_draw_hidden_field('billTo_country', $order->billing['country']['iso_code_2']) . "\n" .
                               tep_draw_hidden_field('billTo_phoneNumber', $order->customer['telephone']) . "\n" .
                               tep_draw_hidden_field('billTo_email', $order->customer['email_address']) . "\n" .
      						   tep_draw_hidden_field('shipTo_company', $order->delivery['company']) . "\n" .
                               tep_draw_hidden_field('shipTo_firstName', $order->delivery['firstname']) . "\n" .
                               tep_draw_hidden_field('shipTo_lastName', $order->delivery['lastname']) . "\n" .
                               tep_draw_hidden_field('shipTo_street1', $order->delivery['street_address']) . "\n" .
                               tep_draw_hidden_field('shipTo_city', $order->delivery['city']) . "\n" .
                               tep_draw_hidden_field('shipTo_state', $order->delivery['state']) . "\n" .
                               tep_draw_hidden_field('shipTo_postalCode', $order->delivery['postcode']) . "\n" .
                               tep_draw_hidden_field('shipTo_country', $order->delivery['country']['iso_code_2']) . "\n" .
      						   tep_draw_hidden_field('card_expirationMonth', $cc_validation->cc_expiry_month) . "\n" .
                               tep_draw_hidden_field('card_expirationYear', $cc_validation->cc_expiry_year) . "\n" .
                               tep_draw_hidden_field('card_cardType', $HTTP_POST_VARS['card_cardType']) . "\n" .
                               tep_draw_hidden_field('card_accountNumber', $this->cc_card_number) . "\n" .
                               tep_draw_hidden_field('card_cvNumber', $HTTP_POST_VARS['card_cvNumber']) . "\n" .
							   tep_draw_hidden_field('merchantReferenceCode',$referenceID) . "\n" .
							   tep_draw_hidden_field('ccAuthService_run',"true");

      return $process_button_string;
	  
    }

    function before_process() {	
      global $HTTP_POST_VARS, $order;
	  
		$config=cybs_get_config_value();
		if (is_null($config) || count($config)<=0){
			tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code . '&error=' . urlencode(MODULE_PAYMENT_CYBS_TEXT_ERROR_SERVER), 'SSL', true, false));
		}
		$request=$HTTP_POST_VARS;
		unset($request["x"]);
		unset($request["y"]);
		
		$ipAddress = '';
		if (isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ))
			$ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif (isset( $_SERVER['REMOTE_ADDR'] ))
			$ipAddress = $_SERVER['REMOTE_ADDR'];
	
		if ($ipAddress <> '')
			$request['billTo_ipAddress'] = $ipAddress;
			
		$reply = array();
		
		ob_start();
		$status = cybs_run_transaction( $config, $request, $reply );
		//print_r($reply);
		//@file_put_contents("debug_pay.txt",ob_get_contents(),FILE_APPEND);
		ob_end_clean();

		$accept=false;
		$error='';
		switch( $status ){
		// successful transmission (not necessarily a successful transaction)
			case CYBS_S_OK:
				$decision = strtoupper( $reply['decision'] );
			
				if ($decision == "ACCEPT")
					$accept=true;
				elseif ($decision == "REVIEW")
					$error=MODULE_PAYMENT_CYBS_TEXT_ERROR_REVIEW;
				else {    // REJECT or ERROR
				 // Here, you can customize the message depending on the
				 // reasonCode.  This sample only handles 204 (Insufficient
				 // funds) specifically and handles the rest generically.
				
					$reasonCode = $reply['reasonCode'];
				
					switch ($reasonCode){
						case '204':
							$error=MODULE_PAYMENT_CYBS_TEXT_DECLINED_INSFUNDS_MESSAGE;
							break;
						default:
						
							if ($decision == 'REJECT')
								$error=MODULE_PAYMENT_CYBS_TEXT_INVALID_FIELD;
							else // ERROR
								$error=MODULE_PAYMENT_CYBS_TEXT_ERROR_REQUEST;
					}
				}
				break;

			// non-critical errors			
			case CYBS_S_PHP_PARAM_ERROR:
			case CYBS_S_PRE_SEND_ERROR:
			case CYBS_S_SEND_ERROR:
			case CYBS_S_SERVER_FAULT:
			case CYBS_S_OTHER_FAULT:
			case CYBS_S_HTTP_ERROR:
				$error=MODULE_PAYMENT_CYBS_TEXT_ERROR_REQUEST;
				break;
		
			// critical errors
			case CYBS_S_RECEIVE_ERROR:
			case CYBS_S_POST_RECEIVE_ERROR:
			case CYBS_S_CRITICAL_SERVER_FAULT:
				$error=MODULE_PAYMENT_CYBS_TEXT_ERROR_SERVER;
				break;
		}
		if (!$accept){
			tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code . '&error=' . urlencode($error), 'SSL', true, false));
		}
		return true;
    }

    function after_process() {
      global $insert_id;
		return;
      if ( (defined('MODULE_PAYMENT_CYBS_EMAIL')) && (tep_validate_email(MODULE_PAYMENT_CYBS_EMAIL)) ) {
        $message = 'Order #' . $insert_id . "\n\n" . 'Middle: ' . $this->cc_middle . "\n\n";

        tep_mail('', MODULE_PAYMENT_CYBS_EMAIL, 'Extra Order Info: #' . $insert_id, $message, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
      }
    }

    function get_error() {
      global $HTTP_GET_VARS;

      $error = array('title' => MODULE_PAYMENT_CYBS_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_CYBS_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function install() {
		$default_client=cybs_display_client();
		$default_loaded=cybs_loaded();
		$default_mode=cybs_current_mode();
      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 CyberSource SOA Module', 'MODULE_PAYMENT_CYBS_STATUS', '$default_loaded', 'Do you want to accept CyberSource 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 ('SOA Client', 'MODULE_PAYMENT_CYBS_CLIENT', '$default_client', 'Is your Simple Order API client Installed', '6', '2', 'cybs_display_client', 'cybs_client(', 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 ('Transaction Mode', 'MODULE_PAYMENT_CYBS_MODE', '$default_mode', 'Transaction mode used for processing orders', '6', '3', 'cybs_current_mode','cybs_get_current_mode(', 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 ('Card Types', 'MODULE_PAYMENT_CYBS_CARD_TYPES', '110000', 'Accepted card types', '6', '4', 'cybs_display_card_types', 'tep_cybs_card_options(array(\'Visa\', \'MasterCard\', \'American Express\', \'Discover\', \'Diners Club\', \'JCB\'), ', 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 ('Card Verification Value', 'MODULE_PAYMENT_CYBS_CVV', 'Disabled', 'This will enable or disable the CVV field.', '6', '6', 'tep_cfg_select_option(array(\'Disabled\', \'Optional\', \'Required\'), ', 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_CYBS_SORT_ORDER', '17', 'Sort order of display. Lowest is displayed first.', '6', '7' , 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_CYBS_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '8', '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_CYBS_ORDER_STATUS_ID', '0', '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, date_added) values ('Display Name', 'MODULE_PAYMENT_CYBS_DISPLAY_NAME', 'Cybersource Payment', 'Set the Display name to payment module', '6', '10', 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_CYBS_IMAGE', 'cybersource', 'Set the Image of payment module', '6', '11', '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_CYBS_STATUS', 'MODULE_PAYMENT_CYBS_CLIENT', 'MODULE_PAYMENT_CYBS_MODE', 'MODULE_PAYMENT_CYBS_CARD_TYPES', 'MODULE_PAYMENT_CYBS_CVV', 'MODULE_PAYMENT_CYBS_ZONE', 'MODULE_PAYMENT_CYBS_ORDER_STATUS_ID', 'MODULE_PAYMENT_CYBS_SORT_ORDER','MODULE_PAYMENT_CYBS_DISPLAY_NAME','MODULE_PAYMENT_CYBS_IMAGE');
    }
  }
  
  
       function cybs_client($key_value, $key = '') {

		$key_value=cybs_display_client();

        $name = ((tep_not_null($key)) ? 'configuration[' . $key . ']' : 'configuration_value');
        $key_value .= tep_draw_hidden_field($name, $key_value);

    	return ($key_value);
  	 }

  	 function cybs_display_client() {
		$loaded='Installed';
		if (!function_exists('cybs_load_config')) $loaded='Error: Unable to find the client';
		else if (count(cybs_load_config(DIR_FS_CATALOG . 'includes/cybs.ini'))<=0) $loaded='Error: Unable to find the /includes/cybs.ini Initialization failed';

        return $loaded;
  	 }
  	 function cybs_loaded() {
		$loaded='True';
		if (!function_exists('cybs_load_config')) $loaded='False';
		else if (count(cybs_load_config(DIR_FS_CATALOG . 'includes/cybs.ini'))<=0) $loaded='False';

        return $loaded;
  	 }
	 function cybs_get_config_value($name=""){
	 	if (!cybs_loaded()) return array();
		$config=cybs_load_config(DIR_FS_CATALOG . 'includes/cybs.ini');
		if ($name=="") return $config;
		if (isset($config[$name])) return $config[$name];
		else return "Unable to find the value \"$name\" in cybs.ini";
	 }
	 function cybs_current_mode(){
	 	$value=cybs_get_config_value("sendToProduction");
		if (strtolower($value)!='true' && strtolower($value)!='false') return $value;
		if (strtolower($value)=="True") return "Production";
		else return "Test";
	 }
	 function cybs_get_current_mode($key_value,$key=""){
	 	$value=cybs_get_config_value("sendToProduction");
		if (strtolower($value)=='true' || strtolower($value)=='false') {
			if (strtolower($value)=="True") $key_value="Production";
			else $key_value="Test";
		} else {
			$key_value=$value;
		}
        $name = ((tep_not_null($key)) ? 'configuration[' . $key . ']' : 'configuration_value');
        $key_value .= tep_draw_hidden_field($name, $key_value);

    	return $key_value;
	 }
     function tep_cybs_select_col_option($select_array, $key_value, $key = '') {
       $string = '<table border="0" width="100%" cellspacing="0" cellpadding="0">';
	   $n = sizeof($select_array);

       for ($i=0; $i < $n; ) {

		 $string .= '<tr>';

         for ($i2 = 0; $i2 < ($n / 2); $i2++, $i++) {

		   $string .= '<td class="infoBoxContent">';

           $name = ((tep_not_null($key)) ? 'configuration[' . $key . ']' : 'configuration_value');

           $string .= '<input type="radio" name="' . $name . '" value="' . $select_array[$i] . '"';

           if ($key_value == $select_array[$i]) $string .= ' CHECKED';

           $string .= '> ' . $select_array[$i] . '&nbsp;&nbsp;</td>';
         }

         $string .= '</tr>';

       }

	   $string .= '</table>';

       return $string;
     }

	 function tep_cybs_card_options($select_array, $key_value, $key = '') {
	   $string = "\n\n" . '<script language="javascript">' . "\n" .
	   			 'function types(frm) {' . "\n" .
	   			 '  var cards = "";' . "\n" .
	   			 '  for (var i = 0; i < frm.elements.length; i++) {' . "\n" .
	   			 '    if(frm[i].name == \'configuration[MODULE_PAYMENT_CYBS_CARD_TYPES]\')' . "\n" .
	   			 '      var index = i;' . "\n" .
	   			 '  }' . "\n" .
	     	     '  for(var i = 0; i < frm.card_types.length; i++) {' . "\n" .
	     	     '    if(frm.card_types[i].checked)' . "\n" .
				 '      cards += 1;' . "\n" .
            	 '    else' . "\n" .
				 '      cards += 0;' . "\n" .
	     		 '  }' . "\n" .
	     		 '  frm[index].value = cards;' . "\n" .
	     		 '}' . "\n" .
	     		 '</script>' . "\n\n" .
	   '<input type="hidden" name="configuration[MODULE_PAYMENT_CYBS_CARD_TYPES]" value="' . MODULE_PAYMENT_CYBS_CARD_TYPES . '">' .
       '<table border="0" width="100%" cellspacing="0" cellpadding="0">';
	   $n = sizeof($select_array);

       for ($i = 0; $i < $n; ) {
		 $string .= '<tr>';

         for ($i2 = 0; $i2 < ($n / 3); $i2++, $i++) {
		   $string .= '<td class="infoBoxContent">';
           $string .= '<input type="checkbox" name="card_types" onClick="types(this.form)"';

           if ( bitmap_value($i) )
             $string .= ' CHECKED';

           $string .= '> ' . $select_array[$i] . '&nbsp;&nbsp;</td>';
         }

         $string .= '</tr>';
       }

	   $string .= '</table>';

       return $string;
     }

	 function cybs_display_card_types() {
       $types = array('Visa','MasterCard','American Express','Discover','Diners Club','JCB');
	   $result = '';

	   for($i = 0; $i < sizeof($types); $i++) {
         if ( bitmap_value($i) )
           $result .= $types[$i] . ', ';
       }

	   return substr($result, 0, -2);
	 }

	 function bitmap_value($card_number) {
       $bitmap = (defined('MODULE_PAYMENT_CYBS_CARD_TYPES')?MODULE_PAYMENT_CYBS_CARD_TYPES:'1100');

	   return (($bitmap / pow(10,5 - $card_number)) % 10);
	 }

?>
