<?php
/**
 *  @file
 *  clientexec linkpoint api plugin
 *  (c) 2005 Darrel O'Pry, thing.net communications
 *  email: dopry@darrelopry.com
 *  
 *  -improved comments and code formatting before licensing to CE. -dopry 02/23/2007
 */

// include linkpoint API to  simplify processing, and maintenance
include('class.lpxchange.php');

/**
 * implmentation of _variables callbck.
 * return an array of configuration settings, options and default
 * values for use on the plugin settings form.
 *
 * @param ??
 * @return array
 */
function plugin_linkpoint_variables() {
  // Specification 
  //    itemkey - used to identify variable in your other functions
  //    type - text,textarea,yesno,password,hidden ( hiddens are not visable to the user )
  //    description - description of the variable, displayed in ClientExec
  //    value - default value

  $variables = array (
    "In Signup" => 	array 	(
      "type" => "yesno",
      "description" => "Select YES if you want to include this payment processor in the signup script.",
      "value" => "0"					
    ),
    "Plugin Name" => array (
      "type" => "hidden",
      "description" => "How CE sees this plugin ( not to be confused with the Signup Name )",
      "value" => "LinkPoint"
    ),
    // Required variables.
    "Store" => array (
      "type" => "text",
      "description" => "Please enter your LinkPoint store Name.",
      "value" => ""
    ),
    "Host" => array (
      "type" => "text",
      "description" => "Please enter your linkpoint host.",
      "value" => "secure.linkpt.net"
    ),
    "Port" => array (
      "type" => "text",
      "description" => "Please enter your linkpoint port.",
      "value" => "1129"
    ),
    "Cert" => array (
      "type" => "text",
      "description" => "Please enter the patch to your Linkpoint Digital Certificate.",
      "value" => "/path/to/linkpoint.pem"
    ),


    "RiskThreshold" => array(
      'type' => 'text',
      'description' => 'The LinkShield Risk Score at which you decline transactions.<br>(only used if LinkShield is available with your merchant account)',
      'value' => '',
    ),
    "Live" => array 	(
      "type" => "yesno",
      "description" => "Select Yes to run live transactions, No to run Demo Transactions",
      "value" => ""
    ),
    "Demo Approve" => array (
      "type" => "yesno",
      "description" => "Select yes to approve trasnactions in Demo Mode and no to decline transactions in DemoMode",
      "value" => ""
    ),

    "Accept CC Number" => array (
      "type" => "hidden",
      "description" => "Selecting YES allows the entering of CC numbers when using this plugin type. No will prevent entering of cc information",
      "value" => "1"
    ),

    "Visa" => array (
      "type" => "yesno",
      "description" => "Select YES to allow Visa card acceptance with this plugin.  No will prevent this card type.",
      "value" => "1"
    ),
    "MasterCard" => array (
      "type" => "yesno",
      "description" => "Select YES to allow MasterCard acceptance with this plugin. No will prevent this card type.",
      "value" => "1"
    ),
    "AmericanExpress" => array (
      "type" => "yesno",
      "description" => "Select YES to allow American Express card acceptance with this plugin. No will prevent this card type.",
      "value" => "1"
    ),
    "Discover" => array (
      "type" => "yesno",
      "description" => "Select YES to allow Discover card acceptance with this plugin. No will prevent this card type.",
      "value" => "0"
    ),
    "Invoice After Signup" => array (
      "type" => "yesno",
      "description" => "Select YES if you want an invoice sent to customer after signup is complete.  Only used for offline plugins",
      "value" => "1"
    ),
    "Signup Name" => array (
      "type" => "text",
      "description" => "Select the name to display in the signup process for this payment type. Example: eCheck or Credit Card.",
      "value" => "credit card"
    ),
    "Dummy Plugin" => array (
      "type" => "hidden",
      "description" => "1 = Only used to specify a billing type for a customer. 0 = full fledged plugin requiring complete functions",
      "value" => "0"
    ),
    "Auto Payment" => array (
      "type" => "hidden",
      "description" => "No description",
      "value" => "1"
    ),
    "30 Day Billing" => array (
      "type" => "hidden",
      "description" => "Select YES if you want ClientExec to treat monthly billing by 30 day intervals.  If you select NO then the same day will be used to determine intervals.",
      "value" => "0"
    )
  );
  return $variables;
}

/**
 * implmentation of _singlepayment callbck.
 * call back for users wanting to make a single payment.
 * In this plug in this callback chains the autopayment
 * function as per the authorizenet plugin.
 *
 * @param $params array
 *   payment options.
 * @return ??
 */
function plugin_linkpoint_singlepayment($params) { // when set to non recurring
//Function used to provide users with the ability
//Plugin variables can be accesses via $params['plugin_[pluginname]_[variable]'] (ex. $params['plugin_paypal_UserID'])
return plugin_linkpoint_autopayment($params);
}

/**
 * implementation of the _autopayment callback.
 * This call back handles automatically processing payment
 * transactions .
 *
 * @param $params array
 *   plugin configuration and transaction details.
 * @return ??
 */
function plugin_linkpoint_autopayment($params){
  // Identify our self to linkoint.setup linkpoint connection/auth vars
  $myorder['configfile'] = $params['plugin_linkpoint_Store'];

  // commented out since, I was unable to figure out how to merge a payment a fraud plugin
  // at the time of writing this code, I do not think fruad plugins were supported.
  // left for future adventurers to think about or remove.
  /*
  if ($params['isSignup']==1) {
  	$myorder['order_type'] = "PREAUTH";     //do a pre auth on signup so we can get fraud data if available
  	$bolInSignup = true;
  } 
  else {  
  */
    $myorder['ordertype']  = 'SALE'; //we're gonna process w/o fraud protection
  /*
    $bolInSignup = false;
  }
  */

  // Check if the plugin is configure to run in live mode and the 
  // control panel is not in demo demo mode.
  if ($params['plugin_linkpoint_Live'] && !$params['demoMode'])  {
    $myorder[result] = 'LIVE';
  } 
  else {
    switch($params['plugin_linkpoint_Demo Mode']) {
      case 1: $myorder['result']="GOOD"; 	break;
      case 2: $myorder['result']="DUPLICATE";	break;
      case 3: $myorder['result']="DECLINE"; 	break;
      default: $myorder['result']="GOOD"; //assume good
    }
  }

  // Setup transaction options in a structured array that
  // parallels linkpoints XML format.

  // Harcode Electronic Commerce Initiated.
  $myorder['transactionorigin'] = "ECI"; 

  // Add a time stamp to the oid to help prevent duplicate transactions
  // and allow us to potentially track/refund multiple payments against
  // an invoice.
  $myorder['oid']               = $params['invoiceNumber'].date('dmHis');

  // I'm not quite sure what the spec was on this anymore.
  $myorder['terminaltype']      = "UNSPECIFIED";

  // Get IP of person initiating transaction.
  if (getenv('HTTP_X_FORWARDED_FOR')) {
    $ip   = getenv('HTTP_X_FORWARDED_FOR');
  } else {
    $ip   = getenv('REMOTE_ADDR');
  }
  $myorder['ip'] = $ip; //needed for ip blocking/fraud protection


  $myorder['chargetotal'] = $params['invoiceTotal'];

  // card info
  $myorder['cardnumber']   = $params['userCCNumber'];
  $myorder['cardexpmonth'] = substr($params['userCCExp'], 0, 2);
  $expLen = strlen($params['userCCExp']);

  $myorder['cardexpyear']  = substr($params['userCCExp'], $expLen - 2, $expLen);
  // commented out code for CVV2 values. You could use a client profile field to get
  // that data here to save a % per transaction.
  /*
  $myorder['cvmvalue'] = $params[??]
  if ($myorder['cvmvalue']) { 
  	$myorder['cvmindicator']     = "provided";
  }
  else {
  */
    $myorder['cvmindicator']     = 'not_provided';
  /*
  }
  */

  // BILLING INFO
  $myorder['name']     = $params['userFirstName'] .' '. $params['userLastName'];

  // Set a company name.  IIRC a value is required and NA was linkpoints recommended placeholder.
  if ($params['userOrganization']=='') {
    $myorder['company'] = "NA";
  }
  else {
    $myorder['company'] = $params['userOrganization'];
  }


  $myorder['address1'] = $params['userAddress'];
  $myorder['city']     = $params['userCity'];
  $myorder['state']    = $params['userState'];
  $myorder['country']  = $params['userCountry'];
  $myorder['phone']    = $params['userPhone'];
  $myorder['email']    = $params['userEmail'];
  
  // Get numeric portion of address for AVS.
  preg_match('/(^\d*)\s/', $params['userAddress'], $matches);
  $myorder['addrnum']  = $matches[0];
  $myorder['zip']      = $params['userZipcode'];

  // Order item detail for linkpoint.
  // It would be nice if all package data for the invoice was passed
  // then you could itemize you transactions in linkpoint as well.
  $myorder['items']['item']['id']          = $params['invoiceNumber'];
  $myorder['items']['item']['description'] = $params['invoiceDescription'];
  $myorder['items']['item']['price']       = $params['invoiceTotal'];
  $myorder['items']['item']['quantity']    = '1';


  // lpxchange class will use this path for curl.
  if ($params['pathCurl'] != '') {
    $myorder['pathCurl'] = $params['pathCurl'];
  }


  // Set up setup linkpoint connection vars
  // from plugin settings
  $host       = $params['plugin_linkpoint_Host'];
  $port       = $params['plugin_linkpoint_Port'];
  $keyfile    = $params['plugin_linkpoint_Cert'];

  // Instantiate the lpxchange class.
  $lpx = new lpxchange($host, $port, $keyfile, false, false);

  // Send payment data to the linkpoint gateway.
  $linkpointResult = $lpx->process_payment($myorder);

  // need to tell gateway plugin class not to reset docroot since we are calling directly
  $bolLeavePath=true;
  include_once("classes/class.gateway.plugin.php");

  // Create plug in class to interact with CE.
  $cPlugin = new Plugin($params['invoiceNumber']);
  $result = $linkpointResult['r_approved'];
  
  switch ($result) {
    case "APPROVED": 	
      // Handle approved transactions
      $cPlugin->PaymentAccepted($params['invoiceAmount'], $linkpointResult[r_message] .' (LP Approval: '. $linkpointResult['r_code'] .'; Ref: '. $linkpointResult['r_ref'] .'; Time: '. $linkpointResult['r_time']. ')',0);					
      // updated to return an empty string for CE 2.8.2 compatability by Modified by Ryan Wilson, ClanBaseLive.com
      $tReturn = "";
      break;

    case "DECLINED":
      // Handle declined transactions
      $tReturn = 'DECLINED '. $linkpointResult['r_error'] .';AVS: '. $linkpointResult['r_avs'] .'; '. $linkpointResult['r_message'] .' (ref: '. $linkpointResult['r_ordernum'] .')';
      $cPlugin->PaymentRejected($tReturn,0);					
      break;

    case 'FRAUD':
      // Handle fraud transactions similar to declined transactions, but return a different
      // string.
      $tReturn = 'FRAUD '. $linkpointResult['r_error'] .' (ref: '. $linkpointResult['r_ordernum'] .')';
      $cPlugin->PaymentRejected($tReturn, 0);
      break;

    default:
      // @todo: update error string.
      $tReturn = "Processing Error Notify Administrator or support@example.com";
      $cPlugin->PaymentRejected( $tReturn,0);
      break;
  }
  return $tReturn;
}
?>
