<?php
if (session_status() == PHP_SESSION_NONE) {
    if(!isset($_SESSION)) session_start();
}

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

function analyzeWord($word, $table=null)
{
	$slots = getKbInstanceSlots($word,$table, false);
	if (strlen($table) == 0)
		return $slots;
	return $slots? $slots["caption"] : null;
}

function getKbInstanceSlots($word, $table, $returnSlotsCaptions, $getInstances = false)
{
    $mysqli = sqlCreateConnection("getKbInstanceSlots");
    $intuscanWordHost = getSystemSettingsProp($mysqli, "intuscanWordHost");
    $intuscanWordPort = getSystemSettingsProp($mysqli, "intuscanWordPort");
    sqlClose($mysqli, "getKbInstanceSlots System stats");
	global $lang_override_arr;
	
	$filePath = "a:\\word.txt";
	//$word = "U.S.A";
	
	$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";
	    //die ("\nserver down");
	    return "";
	}
	
	$result = socket_connect($socket, $intuscanWordHost, $intuscanWordPort);
	if ($result === false) {
	    write_to_log("ERROR", "socket_connect() failed. host: $intuscanWordHost and port: $intuscanWordPort");
	    //echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
	    //die ("\nserver down");
	     return "";
	}	
		         
	//$base64Contents = base64_encode($contents);	
	$base64Contents = base64_encode($word);
	
	$lang_override = implode(',',$lang_override_arr);
	
	$out = "<IVEnvelope><Request id=\"1\"><AnalyzeFile><InputParameters>";               
	$out .= "<ConfigOverrides><item path=\"/Configuration/Execution/engines/engine[@name='IVNlp']/modules/module[@name='mainChartParser']/@status\" value=\"off\"/>" .
			  //expandInstances is needed to get captions of slot instances (e.g. united-states -> United States)
			  ($returnSlotsCaptions? "<item path=\"/Configuration/Execution/export/rdf/@expandInstances\" value=\"yes\"/>" : "") .
              "<item path=\"/Configuration/Execution/engines/engine[@name='IVPre']/forcedLanguage/@name\" value=\"$lang_override\"/></ConfigOverrides>";	
	$out .= "<FileMetaParameters><structured><slot name=\"TerminalSystemId\"><integer>" . "1" . "</integer></slot></structured></FileMetaParameters><FilePath>" . $filePath . "</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) > 30)
		{
			//$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 "";
		}
	}
	
	socket_close($socket);			
	
	$lastEnvPosition = strrpos($output, "<IVEnvelope>");
	$msg = substr($output, $lastEnvPosition, strlen($output));
	dumpDbg("analyzeWord_msg", $msg);
	return getKbInstanceSlotsFromRDF($msg,$table, $returnSlotsCaptions, $getInstances);
}


function getKbInstanceSlotsFromRDF($output,$table, $returnSlotsCaptions, $getInstances = false)
{		
	$blob = $output;
	$xml = new DOMDocument();
	$loadRes = $xml->loadXml($blob);
	if($loadRes == false)
 	   	$loadRes = $xml->loadXml($blob);
 	   
 	$xpathXml = new DOMXpath($xml);
 	$b64 = $xml->getElementsByTagName("Base64")->item(0)->textContent;
 	$text = iconv("UTF-16LE", "UTF-8", base64_decode($b64));
 	
	$tripples = $xml->getElementsByTagName("FileTriples")->item(0);
	//Insert rdf result to joseky
	$aggr = $tripples->getElementsByTagName("AggregatedRDF")->item(0);
	$content = $aggr->firstChild;
	$qname2node = array();
	$pred2inst = array();
	$class2subClasses = array();
	$subClass2classes = array();
	rdf2structs("dig", $tripples->getElementsByTagName("DigestRDF")->item(0)->firstChild->wholeText, $qname2node, $pred2inst, $class2subClasses, $subClass2classes);
	dumpDbg("qname2node_getKbInstanceSlotsFromRDF", $qname2node);
	
	//for analyzing specific word (as in user-location background) - return just ont instances
	if($getInstances){
	    $instances = [];
	    $iv = "http://www.intuview.com/ontology#";
	   foreach($qname2node["dig"] as $key=>$element){
	       if(substr($key, 0, strlen($iv)) === $iv){
	           
	           $instances[] = $element;
	           
	       }
	   }
	   return $instances;
	}
	
	$xmlDom = new DOMDocument();
	$xmlDom->loadXML($content->wholeText);
	$iv = "http://www.intuview.com/ontology#";
	$xpathDom = new DOMXpath($xmlDom);
		
		
	/////////////////////////////////////////////////////////////
	// 
	// use for ontology concet or when we don't have the table
	//
	/////////////////////////////////////////////////////////////
	if (strlen($table) == 0){
		$restricted_tabels = array("http://www.intuview.com/ontology#Family-name" => "Family-name",
									"http://www.intuview.com/ontology#Given-name" => "Given-name",
									"http://www.intuview.com/ontology#Name-component" => "Name-component",
									"http://www.intuview.com/ontology#Acronym" => "Acronym",
									"http://www.intuview.com/ontology#Indicator-kunya" => "Indicator-kunya",
									"http://www.intuview.com/ontology#Arabic-name-part-indicator" => "Arabic-name-part-indicator",
									"http://www.intuview.com/ontology#Persian-name-part-indicator" => "Persian-name-part-indicator",
									"http://www.intuview.com/ontology#Person-name-prefix" => "Person-name-prefix",
									"http://www.intuview.com/ontology#Person-name-suffix" => "Person-name-suffix",
									"http://www.intuview.com/ontology#Western-name-part-indicator" => "Western-name-part-indicator");
		
		
		rdf2structs("dig", $content->wholeText, $qname2node, $pred2inst, $class2subClasses, $subClass2classes);
		foreach ($qname2node["dig"] as $type){
			if (!is_array($type["rdf:type"]))			
				if (!array_key_exists($type["rdf:type"], $restricted_tabels))					
					if (array_key_exists("iv:caption", $type)){
					    if (is_array($type["iv:caption"]) && array_key_exists("en", $type["iv:caption"])){
							$caption[strtolower($type["iv:caption"]["en"])] = $type["iv:caption"]["en"];
					       }
						else{
							$caption[strtolower($type["iv:caption"])] = $type["iv:caption"];			
						}
				}
		}
		
		foreach ($subClass2classes as $k => $v){
			if (!in_array($k, $restricted_tabels)){
				$k = str_replace("-","_",$k);
				$concept[strtolower($k)] = strtolower($k);
			}
		}
		$ret["caption"] = $caption ?? null;
		$ret["concept"] = $concept ?? null;
		//Ading entity tables if we didn't found them.
		$entityArr = array("person_object", "organizational_identity", "place_object", "event");
		foreach ($entityArr as $e){
		    if(!empty($ret["concept"])){
    			if (!array_key_exists($e, $ret["concept"])){
    				$ret["concept"][$e] = $e;
    			}
		    }
		}
		return $ret;
	}
	$results = $xpathDom->evaluate("/rdf:RDF/rdf:Description[rdf:type/@rdf:resource='$iv$table' or iv:entity-type/@rdf:resource='$iv$table']");				
	
	$result = array();
	if (!$results || ! $results->length)
		return $result;

	
	$result["rdfAbout"] = $results->item(0)->attributes->getNamedItem("about")->nodeValue;
	foreach ($results->item(0)->childNodes as $slotNode)
	{
		$key = $slotNode->nodeName;
		$keySplit = explode(":", $key);
		if ($keySplit && count($keySplit) == 2)
			$key = $keySplit[1];
		
		if ($slotNode->hasAttributes())
		{
			$lang = $slotNode->attributes->getNamedItem("lang");
			if ($lang)
			{
				if ($lang->nodeValue == "en")
					$value = $slotNode->firstChild->nodeValue;
				else
					continue;
			}
			else {
				$resource = $slotNode->attributes->getNamedItem("resource");
				if ($resource)
				{
					//write_to_log("TRACE", "resource->nodeValue: $resource->nodeValue");
					if ($returnSlotsCaptions && array_key_exists($resource->nodeValue, $qname2node["dig"]))
					{
						$caption = $qname2node["dig"][$resource->nodeValue]["iv:caption"];
						if ($caption)
							$value = is_array($caption)? $caption["en"] : $caption;
						else
							$value = unqualifyName($resource->nodeValue);
						//write_to_log("TRACE", "resource->nodeValue caption: $caption, value: $value");
					}
					else
					$value = unqualifyName($resource->nodeValue);
				}
				else
					continue;
			}
		}
		else if ($slotNode->hasChildNodes())
			$value = $slotNode->firstChild->nodeValue;
		else
			continue;
		
		if ($value && is_string($value))
		{
			$result[$key] = $value;
		}
	}
	dumpDbg("getKbInstanceSlotsFromRDF_result", $result);
	return $result;
}
?>