<?php
//if(!isset($_SESSION)) session_start();

//echo $_SERVER['DOCUMENT_ROOT'];
/*
if (empty($CURRENT_SOURCE_FOLDER))
$CURRENT_SOURCE_FOLDER = dirname(__FILE__);
set_include_path($CURRENT_SOURCE_FOLDER . "/easyrdf-0.6.2/lib/");

require_once $CURRENT_SOURCE_FOLDER . "/demosettings.php";
require_once $CURRENT_SOURCE_FOLDER . "/easyrdf-0.6.2/lib/EasyRdf.php";
require_once $CURRENT_SOURCE_FOLDER . "/easyrdf-0.6.2/examples/html_tag_helpers.php";
*/

global $rdfstoreHost;
global $rdfstoreCmHost;

$RDF_IV_NS = "http://www.intuview.com/ontology#";

function executeSparql($sparql, $port="2020"){	
	$tmp = executeSparqlOnService($sparql, NULL, $port);
	return $tmp;
}

function executeSparqlOnCmService($sparql, $service){
  	global $rdfstoreCmHost;
  	if(is_null($service))
  		$service = "ont";
  	//$url = "http://localhost" . ":" . "2020" . "/" . $service;
  	$url = "http://" . $rdfstoreCmHost . ":" . "8080" . "/" . $service;
  	
	$fields = array(
		'query'=>urlencode($sparql),
		'output'=>urlencode('json')
    );
	foreach($fields as $key=>$value) {
		$fields_string .= $key.'='.$value.'&';
	}
	rtrim($fields_string,'&');

	$ch = curl_init();
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_TIMEOUT,60);
	$results = curl_exec($ch);
	curl_close($ch);
	if ($results === false)
	{
		//print_r($query);
		//echo "-----<br>";
		//print_r($ch);
		//echo "<br> result-$results";
		//die("joseky problem");
	}
  	$json_a=json_decode($results,true);
  	return $json_a;
  }

  function executeSparqlOnService($sparql, $service, $port="2020"){
  	global $rdfstoreHost;
  	if(is_null($service))
  		$service = "ont";
  	//$url = "http://localhost" . ":" . "2020" . "/" . $service;
  	$url = "http://" . $rdfstoreHost . ":" . $port . "/" . $service;
  	
	$fields = array(
		'query'=>urlencode($sparql),
		'output'=>urlencode('json')
    );
	foreach($fields as $key=>$value) {
		$fields_string .= $key.'='.$value.'&';
	}
	rtrim($fields_string,'&');

	$ch = curl_init();
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	$results = curl_exec($ch);
	curl_close($ch);

  	$json_a=json_decode($results,true);
  	return $json_a;
  }

  function buildBasicSparql($selectWhereStr){
  	$sparql = "PREFIX iv:   <http://www.intuview.com/ontology#>
				PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
				PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" . $selectWhereStr;
	return $sparql;
  }

  function unqualifyName($resourceName){
      if(empty($resourceName)){
          return "";
      }
  	if (is_array($resourceName))
  	{
  		write_to_log("WARNING", "cannot unqualifyName of an array: " . print_r($resourceName, true));
  		return $resourceName;
  	}
  	$pos = stripos($resourceName, "#");
  	if($pos != FALSE){
  		$resourceName = substr($resourceName, $pos + 1);
  	}
  	else{
  		$pos = strrpos($resourceName, "/");
  		if($pos != FALSE){
  			$resourceName = substr($resourceName, $pos + 1);
  		}
  	}
  	return $resourceName;
  }

  function isQualified($inst){
  	$pos = stripos($resourceName, "#");
  	return ($pos != FALSE);
  }

  function qualifyName($resourceName, $doc){
  	if($doc == "ont"){
  		return "http://www.intuview.com/ontology#" . $resourceName;
  	}else{
  		return "http://www.intuview.com/doc" . $doc . "#" . $resourceName;
  	}
  }
    
  function insertRDF($content, $docId,$port){  	
  	$graph = new EasyRdf_Graph();	
	$graph->parse(str_replace("\\"," ", $content->wholeText), "guess", "http://www.intuview.com/ontology#");	
	//for test
	//$graph->parse(str_replace("\\"," ", $content), "guess", "http://www.intuview.com/ontology#");
	
	$ntriples = $graph->serialise("ntriples");
	$ntriples = str_replace("_:genid", "_:genid_".$docId."_", $ntriples);	//replace anonymous nodes, e.g. _:genid1 -> _genid_doc1_1
	//echo $ntriples;
	$tarr = explode("\n", $ntriples);
	$ttmp = "";
	for($i = 0; $i < count($tarr) ; $i++){
		$line = $tarr[$i];
		if (0 === strpos($line, "_:genid"))
		{
			$genid = explode(" ", $line)[0];
			if (!array_key_exists($genid, $genids))
				$genids[$genid] = null;
		}
	}

	for($i = 0; $i < count($tarr) ; $i++){
		$line = $tarr[$i];
		$lineArr = explode(" ", $line);
		$subject = $lineArr[0];
		$object = $lineArr[2];
		if (0 === strpos($object, "_:genid") && array_key_exists($object,$genids))
		{
			$genids[$object] = $line . "\r\n";
			continue;
		}
		else if (0 === strpos($subject, "_:genid") && array_key_exists($subject,$genids))
		{
			$ttmp .= $genids[$subject];
			unset($genids[$subject]);
		}
		$ttmp .= $tarr[$i] . "\r\n";
		if($i % 140 == 0 && $i > 0){

			$sparql = "PREFIX iv:   <http://www.intuview.com/ontology#>
   			  PREFIX rdf: 	<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
   			  INSERT { " . $ttmp . "}
   			  WHERE { }";
			insertQuery($sparql,$port);
			$ttmp = "";
		}
	}

	if($i % 140 > 0){
		$sparql = "PREFIX iv:   <http://www.intuview.com/ontology#>
   			  PREFIX rdf: 	<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
   			  INSERT { " . $ttmp . "}
   			  WHERE { }";
			insertQuery($sparql,$port);
			$ttmp = "";
	}

  }

  function insertQuery($query,$port){  
  //Oz test:
  //$tmpHandle = fopen("C:/insertQuery.txt", 'a');
  //fwrite($tmpHandle, $query . "\r\n");
  //fclose($tmpHandle);
  //file_put_contents("C:/insertQuery.txt", $query . "\r\n", FILE_APPEND );
  
  	global $rdfstoreHost;
  	//$url = "http://localhost" . ":" . "2020" . "/update/service";
  	$url = "http://" . $rdfstoreHost . ":" . $port . "/update/service";
			$fields = array(
				'request'=>urlencode($query)
    		);
    		foreach($fields as $key=>$value) {
				$fields_string .= $key.'='.$value.'&';
			}
			rtrim($fields_string,'&');

			$ch = curl_init();

			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_POST,count($fields));
			curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
			curl_setopt($ch,CURLOPT_TIMEOUT,10);
			
			$results = curl_exec($ch);			
			curl_close($ch);
			if ($results === false)
			{
				print_r($query);
				echo "-----<br>";
				print_r($ch);
				echo "<br> result-$results";
				//die("joseky problem");
			}
				
			/*print_r($query);
			echo "-----<br>";
			print_r($ch);
			die("<br> result-$results");*/			
  }
?>