<?php

// Simple Grid Protocol 1.04 - Copyright (c) Brendan Kosowski 2004, 2005, 2015

// *** user defined variables ***

// *** SET TRACKING SERVER IP & TOKEN ***
$track_ip = "10.77.123.2";
$token = "abc123xyz";

// *** LISP TO EVALUATE *** e.g.: (+ 7 (* 6 5))
$eval = "(+ 7 (* 6 5))";

// *** end user defined variables ***

// *** main ***

// get best node and send lisp to grid for evaluation
$best_ip = get_best_node($track_ip, $token);
$result = porta($best_ip, $token, $eval);
echo "<pre>";
echo "Node IP = $best_ip\n";
echo "Lisp = $eval\n";
echo "Result = $result\n";
echo "</pre>";

// *** end main ***


function get_best_node($xtrack_ip, $xtoken) {

	// begin get node info
	$url = "http://{$xtrack_ip}/cgi-bin/xml_show_track.lisp";
	$fields = array(
				'token' => urlencode($xtoken),
			);

	// prep data for POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string, '&');

	// open connection
	$ch = curl_init();

	// set options
	curl_setopt($ch,CURLOPT_URL, $url);
	curl_setopt($ch,CURLOPT_POST, count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

	// execute post
	$string = curl_exec($ch);
	
	// close connection
	curl_close($ch);

	// strip node ip & xml capability from results
	$node = array();
	$xml = simplexml_load_string($string);
	$xr = explode("(\"", $xml->result);
	foreach ($xr as $key => $value) {
		if($key > 0) {
			$xval = explode("\"", $value);
			$node[$key - 1]['ip'] = $xval[0];
			$xval = explode(":XML ", $value);
			$xxval = explode("))", $xval[1]);
			$node[$key - 1]['xml'] = $xxval[0];
		}	
	}
		
	// best ip is first with xml capability
	for($i = 0; 1; $i++) {
		if($node[$i]['xml'] == "T") {
			$best_ip = $node[$i]['ip'];
			break;
		}
	}
	return $best_ip;
}


function porta($xbest_ip, $xtoken, $xeval) {

	// begin send lisp to grid for evaluation
	$url = "http://{$xbest_ip}/cgi-bin/xml_cpurs.lisp";
	$fields = array(
				'token' => urlencode($xtoken),
				'eval' => urlencode($xeval),
			);

	// prep data for POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string, '&');

	// open connection
	$ch = curl_init();

	// set options
	curl_setopt($ch,CURLOPT_URL, $url);
	curl_setopt($ch,CURLOPT_POST, count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

	// execute post
	$string = curl_exec($ch);

	// close connection
	curl_close($ch);

	// get result of lisp evaluation from xml
	$xml = simplexml_load_string($string);
	$xr = $xml->result;
	return $xr[0];
}
?>
