<?php

include("loginCheckPoint.php");
include_once("authorizations.php");
require_once("demosettings.php");

function analayzeWord($word)
{		
	global $intuscanHost;
	global $intuscanPort;
	
	$contentType = "newfile";
	
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($socket === false) {
	    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
	    return;
	    //die ("\nserver down");
	}
	
	$result = socket_connect($socket, $intuscanHost, $intuscanPort);
	if ($result === false) {
		
	    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
	    return;
	    //die ("\nserver down");
	}	
	
	
	if(strlen($contents) == 0){
		// error
	}
		         
	//$base64Contents = base64_encode($contents);	
	$base64Contents = base64_encode($word);
				
	$out = "<IVEnvelope><Request id=\"1\"><AnalyzeFile><InputParameters>";               
	$out .= "<ConfigOverrides><item path=\"/Configuration/Execution/engines/engine[@name='IVNlp']/modules/module[@name='mainChartParser']/@status\" value=\"off\"/>" .
              "<item path=\"/Configuration/Execution/engines/engine[@name='IVPre']/forcedLanguage/@name\" value=\"english,french,spanish\"/></ConfigOverrides>";	
	$out .= "<FileMetaParameters><structured><slot name=\"TerminalSystemId\"><integer>" . "1" . "</integer></slot></structured></FileMetaParameters><FilePath>" . "dummy.txt" . "</FilePath><FileContent><Base64>" . $base64Contents . "</Base64>";
	$out .= "</FileContent></InputParameters><OutputParameters><FileText/><FileReport/><FileMetaParameters/><FileTriples/></OutputParameters></AnalyzeFile></Request></IVEnvelope>";
	socket_write($socket, $out, strlen($out));
	
	socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>3, "usec"=>0));
	$output="";	
	$begin_time = time();		
	while(true){
		$output = $output . socket_read($socket, 1024);
		$pos = strpos($output, "Completed");
		if (strpos($output, "Failed")){
			//$res = $mysqli->query("UPDATE files set files.session='" . $output . "'  where id=" . $docId);
			echo "UPDATE files set files.session='" . $output . "'  where id=" . $docId;
			return;
		}
		if($pos !== false){
			$ending = strpos($output, "</IVEnvelope>", $pos);
			if($ending !== false)
				break;
		}	
		$t = time();
		if (($t - $begin_time) > 180)
		{
			//$res = $mysqli->query("UPDATE files set files.session='time_out " . $output . "'  where id=" . $docId);
			echo "UPDATE files set files.session='time_out " . $output . "'  where id=" . $docId;
			return "timeout";
		}
	}
	
	socket_close($socket);			
	
	$lastEnvPosition = strrpos($output, "<IVEnvelope>");
	$msg = substr($output, $lastEnvPosition, strlen($output));
	//$repmsg = str_replace("\"", "\\\"", $msg);
	
			
	$arr = array();
	$arr[msg] = $msg;
	$arr[docId] = $docId;
	//run in background
	//$cmd = "c:\\xampp\\htdocs\\AllInOneWeb\\cnm_batch.bat " . $docId;
	//pclose(popen("start /B ". $cmd, "r"));
	print_r($arr);	
	return $arr;
	
}
?>