<?php

include_once("config.php");
include_once("sparql.php");
include_once("sql.php");
include_once("lexparser.php");
include_once("transliterator.php");

function queryAllTriples($qname){
	$query = "select ?s ?v";
	$query .= " where { <$qname> ?s ?v . }";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;
}

function queryPropertyRange($qname){
	$query = "select ?r";
	$query .= " where { {<$qname> rdfs:range ?r} 
					UNION 
					{
						?sp rdfs:subPropertyOf <$qname> .
						FILTER (?sp != <$qname>)
						?sp rdfs:range ?r .
					}
				}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;
}

function getConceptPropertiesValueCount($qname){
	$query = "select distinct ?s ?i
			  where {
			  	?s rdf:type rdf:Property .
			  	FILTER(?s != <http://www.intuview.com/ontology#package>) .
			  	{
			  		?su iv:direct-property ?s .
			  		?su rdfs:domain <$qname> .
			  		?su rdf:type rdf:Property .
			  		?i rdf:type <$qname> .
			  		?i ?s ?v .
			  	}
			  	UNION
			  	{
			  		OPTIONAL {?s iv:direct-property ?dp } .
					FILTER(!bound(?dp)) .
			  		?s rdfs:domain <$qname> .
			  		?i rdf:type <$qname> .
			  		?i ?s ?v .
			  	}
			}";
	
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	$results = array();
	//print_r($json);
	foreach ($json['results']['bindings'] as $x){
		if (!isset($results[$x["s"]["value"]]))
			$results[$x["s"]["value"]] = 1;
		else
			$results[$x["s"]["value"]] = $results[$x["s"]["value"]] + 1; 
	}
	
	return $results;
}

function slotValuBreakdown($slotQName, $qname){
	//echo "$slotQName, $qname";
	$query = "select distinct ?i ?il ?v ?vl
			  where {
			  	?i rdf:type <$qname> .
			  	?i <$slotQName> ?v .
			  	?i rdfs:label ?il .
			  	OPTIONAL{
			  		?v rdfs:label ?vl .
			  	}
			}";
	
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	$results = array();
	//print_r($json);
	foreach ($json['results']['bindings'] as $x){
		$tmpArr = array("instance" => $x["i"]["value"], "instanceLabel" => $x["il"]["value"], "value" => $x["v"]["value"]);
		if ($x["v"]["type"] == "uri"){
			$tmpArr["valueLabel"] = $x["vl"]["value"];
		}
		$results[] = $tmpArr;
	}
	return json_encode($results);
}

function label2QName($label){
	global $rdfstoreMode;
	$query = "select ?e";
	
	if ($rdfstoreMode == "regular")
		$query .= " where { ?e rdfs:label '" . $label . "'}";
	else
		$query .= " where { ?e rdfs:label ?l .}"; 
		
	$query = buildBasicSparql($query);
	if ($rdfstoreMode == "combined"){
		$sqlQuery = buildBasicLabelSql($label, true, "e", true);
		$json = executeSqlSparqlOnService($query, $sqlQuery, 1, -1);
	}
	else {
		$json = executeSparqlOnService($query, "ont");
	}
	foreach ($json[results][bindings] as $value){
		$results = $value[e][value];
		break;
	}
	return trim($results);
}

function qname2Label($qname){
	$query = "select ?l
			  where { <$qname> rdfs:label ?l .}";

	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	foreach ($json[results][bindings] as $value){
		$results = $value[l][value];
		break;
	}
	return $results;
}

function getAllPossibleInstanceSlots($qname){
	$query = "select distinct ?s ?l ?t ?tl
			  where {
			  	?s rdf:type rdf:Property .
			  	<$qname> rdf:type ?t .
			  	FILTER(?s != <http://www.intuview.com/ontology#package>) .
			  	{
			  		?su iv:direct-property ?s .
			  		?su rdfs:domain ?t .
			  		?su rdf:type rdf:Property .
			  	}
			  	UNION
			  	{
			  		OPTIONAL {?s iv:direct-property ?dp } .
					FILTER(!bound(?dp)) .
			  		?s rdfs:domain ?t .
			  	}
			  	?s rdfs:label ?l .
			  	?t rdfs:label ?tl .
			} ORDER BY ?tl";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;	
}

function getAllPossibleInstanceSlotsWithValues($qname){
	$query = "select distinct ?s ?l ?t ?tl ?v ?vl
			  where {
			  	?s rdf:type rdf:Property .
			  	<$qname> rdf:type ?t .
			  	FILTER(?s != <http://www.intuview.com/ontology#package>) .
			  	{
			  		?su iv:direct-property ?s .
			  		?su rdfs:domain ?t .
			  		?su rdf:type rdf:Property .
			  	}
			  	UNION
			  	{
			  		OPTIONAL {?s iv:direct-property ?dp } .
					FILTER(!bound(?dp)) .
			  		?s rdfs:domain ?t .
			  	}
			  	?s rdfs:label ?l .
			  	?t rdfs:label ?tl .
			  	OPTIONAL{
			  		<$qname> ?s ?v .
			  		OPTIONAL{
			  			?v rdfs:label ?vl .
			  		}
			  	}
			} ORDER BY ?tl";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;	
}

function getAllPossibleConceptSlots($qname){
	$query = "select distinct ?s ?l ?t ?tl ?r ?rl
			  where {
			  	?s rdf:type rdf:Property .
			  	<$qname> rdfs:subClassOf ?t .
			  	FILTER(?s != <http://www.intuview.com/ontology#package>) .
			  	{
			  		?su iv:direct-property ?s .
			  		?su rdfs:domain ?t .
			  		?su rdf:type rdf:Property .
			  		OPTIONAL {
			  			?su rdfs:range ?r .
			  			OPTIONAL {
			  				?r rdfs:label ?rl .
			  			}
			  		}
			  		OPTIONAL {
			  			?s rdfs:range ?r .
			  			OPTIONAL {
			  				?r rdfs:label ?rl .
			  			}
			  		}
			  	}
			  	UNION
			  	{
			  		OPTIONAL {?s iv:direct-property ?dp } .
					FILTER(!bound(?dp)) .
			  		?s rdfs:domain ?t .
			  		OPTIONAL {
			  			?s rdfs:range ?r .
			  			OPTIONAL {
			  				?r rdfs:label ?rl .
			  			}
			  		}
			  	}
			  	?s rdfs:label ?l .
			  	?t rdfs:label ?tl .
			} ORDER BY ?tl";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;	
}

function getElementDirectTypes($qname){
	$query = "select distinct ?t ?tl
			  where {
			  	<$qname> iv:direct-type ?t .
				?t rdfs:label ?tl .
			}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;	
}

function getElementDirectSuperTypes($qname){
	$query = "select distinct ?t ?tl
			  where {
			  	<$qname> iv:direct-supertype ?t .
				?t rdfs:label ?tl .
			}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;	
}

function getElementGeneralData($qname){
	$query = "select distinct ?s ?v
			  where {
			  	<$qname> ?s ?v .
			  	FILTER(?s = iv:package || ?s = rdfs:label) .
			}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	return $json;
}

function getConceptHierarchy($qname){
	$query = "select ?t ?l ?dt
		  where { <$qname> rdfs:subClassOf ?t .
		  		  	?t rdfs:label ?l .
		  			OPTIONAL {?t iv:direct-supertype ?dt}
		  }";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	$types = array();
	$map = array();

	foreach ($json['results']['bindings'] as $value){
		if (!isset($map[ $value['t']['value'] ])){
			$map[$value['t']['value']] = array('label' =>  $value['l']['value'], 'qname' => $value['t']['value'], 'children' => array(), 
				'childrenStr' => array(), 'types' => array());
		}
		if (!is_null($value['dt'])){
			$map[$value['t']['value']]['types'][] = $value['dt']['value'];
		}
	}

	foreach ($map as $i => $value) {
		for ($j = 0; $j < count($value['types']); $j = $j + 1){
			$map[$value['types'][$j]]['childrenStr'][] = $value['qname'];
		}
	}

	foreach ($map as $i => $value) {
		if (count($value['types']) == 0){
			$types[] = privateBuildNode($value, $map);
		}
	}
	return $types;
}

function getInstanceHierarchy($qname){
	$query = "select ?t ?l ?dt
		  where { <$qname> rdf:type ?t .
		  		  	?t rdfs:label ?l .
		  			OPTIONAL {?t iv:direct-supertype ?dt}
		  }";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	$types = array();
	$map = array();

	foreach ($json['results']['bindings'] as $value){
		if (!isset($map[ $value['t']['value'] ])){
			$map[$value['t']['value']] = array('label' =>  $value['l']['value'], 'qname' => $value['t']['value'], 'children' => array(), 
				'childrenStr' => array(), 'types' => array());
		}
		if (!is_null($value['dt'])){
			$map[$value['t']['value']]['types'][] = $value['dt']['value'];
		}
	}

	foreach ($map as $i => $value) {
		for ($j = 0; $j < count($value['types']); $j = $j + 1){
			$map[$value['types'][$j]]['childrenStr'][] = $value['qname'];
		}
	}

	foreach ($map as $i => $value) {
		if (count($value['types']) == 0){
			$types[] = privateBuildNode($value, $map);
		}
	}
	return $types;
}

function getConceptFlatHierarchy($qname){
	// traversing the tree in order
	
	$types = getConceptHierarchy($qname);
	$results = array();
	for ($i = 0; $i < count($types); $i = $i + 1){
		$results = privateTraverseNodeInOrder($types[$i], $results);
	}
	return $results;
}

function getInstanceFlatHierarchy($qname){
	// traversing the tree in order
	
	$types = getInstanceHierarchy($qname);
	$results = array();
	for ($i = 0; $i < count($types); $i = $i + 1){
		$results = privateTraverseNodeInOrder($types[$i], $results);
	}
	return $results;
}

function privateTraverseNodeInOrder($node, $results){
	$results[] = $node['label'];
	foreach ($node['children'] as $child){
		$results = privateTraverseNodeInOrder($child, $results);
	}
	return $results;
}

function privateBuildNode($node, $map){
	for ($j = 0; $j < count($node[childrenStr]); $j = $j + 1){
		$node[children][] = privateBuildNode($map[$node[childrenStr][$j]], $map);
	}
	return $node;
}

function localLexParse($description){
	$res = parseLexEntry($description);
	if (is_array($res))
		return json_encode($res);	
	else
		return $res;
}

function formatEntry($desc, $lang){
	$res = parseLexEntry($description);
	if (is_array($res) && count($res["tokens"]) > 0){
		return $desc;
	}
	// removing all parentheses
	$desc = str_replace("(", "", $desc);
	$desc = str_replace(")", "", $desc);
	
	$desc = transliterate($desc, $lang);
	
	$tokens = explode(" ", $desc);
	$newDesc = "";
	$count = count($tokens);
	for ($i = 0; $i < $count; $i++){
		$newDesc .= "(" . $tokens[$i] . ")";
	}
	if ($count > 1)
		$newDesc = "(" . $newDesc . ")";
	return $newDesc;
}

function getServersStatus(){
	global $intuScanServers;
	$ret = array();
	foreach ($intuScanServers as $id=>$server){
		if (isServerAlive($id))
			$ret[$id] = true;
		else
			$ret[$id] = false;
	}
	return json_encode($ret);
}

function isServerAlive($id){

	global $intuScanServers;
	
	// sending hello message to the IntuScan server (message is supported as of version 1.2.0.12)
	
	$out = "<IVEnvelope><Request id=\"1\"><Hello/></Request></IVEnvelope>";
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	
	if ($socket === false)
	{
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
	
    	return false;
	}
    socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
	$result = socket_connect($socket, $intuScanServers[$id]["ip"], 
						$intuScanServers[$id]["port"]);
	
	if ($result === false)
	{			
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		return false;
	}	
	//Dosen't work on windows platform
	//$result = socket_send($socket, $out, strlen($out), MSG_EOF);	
	$result = socket_write($socket, $out, strlen($out));
	if ($result === false)
	{
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		return false;
	}
	
	$output="";
	while (true){
		$output = $output . socket_read($socket, 1024);
		$ending = strpos($output, "</IVEnvelope>", $pos);
		if ($ending !== false)	
			break;
	}
	socket_close($socket);

	$lastEnvPosition = strrpos($output, "<IVEnvelope>");
	$msg = substr($output, $lastEnvPosition, strlen($output));
	if (strpos($msg, "OK") === false)
		return false;
	return true;
}

function getAllPackages($userPackageRestricted){
	
	$query = "select distinct ?p
		  where { iv:packages iv:package ?p .}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	$types = array();
	foreach ($json['results']['bindings'] as $value){
		if ($userPackageRestricted == false || substr($value['p']['value'], 0, 1) == '@')
			$types[] = $value['p']['value'];
	}
	asort($types);
	return $types;
}

function isPackageExist($package){
	$query = "select ?p
		  where { iv:packages iv:package '$package' .}";
	$query = buildBasicSparql($query);
	$json = executeSparqlOnService($query, "ont");
	if (count($json['results']['bindings']) > 0)
		return 1;
	return 0;
}

function transliterateDescription($desc, $lang){
	$transliterate = false;
	$output = "";
	for ($i = 0; $i < strlen($desc); $i++){
		if ($transliterate && $desc[$i] == ' ')
			$transliterate = false;
		else if ($transliterate == false){
			if ($i > 0 && $desc[$i - 1] == '('){
				if ($i > 1){
					if ($desc[$i - 2] != ':'){
						$transliterate = true;
					}
				}
				else{
					$transliterate = true;
				}
			}
		}
		if ($transliterate){
			$output .= transliterate($desc[$i], $lang);
		}
		else{
			$output .= $desc[$i];
		}
	}
	return $output;
}

function backTransliterateDescription($desc, $lang){
	$transliterate = false;
	$output = "";
	for ($i = 0; $i < strlen($desc); $i++){
		if ($transliterate && $desc[$i] == ' ')
			$transliterate = false;
		else if ($transliterate == false){
			if ($i > 0 && $desc[$i - 1] == '('){
				if ($i > 1){
					if ($desc[$i - 2] != ':'){
						$transliterate = true;
					}
				}
				else{
					$transliterate = true;
				}
			}
		}
		if ($transliterate){
			$output .= backTransliterate($desc[$i], $lang);
		}
		else{
			$output .= $desc[$i];
		}
	}
	return $output;
}

?>