<?php
include 'analayzeFile.php';

function removeBrackets($str)
{
	$bracketInd = strpos($str, " (");
	if ($bracketInd > 0)
		return substr($str, 0, $bracketInd);
	
	return $str;
}

function appendValue(&$list, $value, $delimiter, $isUnique)
{
	if ($list == null)
		$list = $value;
	else
	{
		if (!$isUnique)
			$found = false;
		else
		{
			$existing = explode($delimiter, $list);
			$found = false;
			foreach ($existing as $e)
				if ($e == $value)
				$found = true;
		}
		if (!$found)
			$list .= $delimiter . $value;
	}
}

function isXML($xml){
   libxml_use_internal_errors(true);

   $doc = new DOMDocument('1.0', 'utf-8');
   $doc->loadXML($xml);

   $errors = libxml_get_errors();

   if(empty($errors)){
       return true;
   }

   $error = $errors[0];
   if($error->level < 3){
       return true;
   }

   $explodedxml = explode("r", $xml);
   $badxml = $explodedxml[($error->line)-1];

   $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
   return $message;
}
//
function extractFacebookUser($content)
{
	if (strpos($content, "id=\"facebook\"")===false)
		return null;
		
	$start = strpos($content, "<h2");
	$end = strpos($content, "</h2>");
	if ($start===false || $end===false || $end<$start)
		return null;
	
	while ($start!==false && $start<$end && $content[$start]=='<')
	{
		$start = strpos($content,">",$start);
		if ($start!==false)
			$start++;	//advance to next html tag
	}
	if ($start==false || $start>=$end)
		return null;
	
	$end = strpos($content, "<", $start);
	if ($end!==false)
		return substr($content,$start,$end-$start);
	else return null;
}
function extractFacebookFriends($content, $delimiter)
{
	if (strpos($content, "id=\"facebook\"")===false)
		return null;
	$prefix = "friends_tab%22%7D\">";
	$start=0;
	$friends = "";
	while(($start = strpos($content,$prefix,$start)) !== false)
	{
		$start += strlen($prefix);
		$end = strpos($content, "<", $start);

		if ($end!==false && $end > $start)
			$friends .= substr($content, $start, $end-$start) . $delimiter;
	}
	return $friends;
}

function AnalyzeText($mysqli, $text)
{
	$content = $text->Request->text;
	//file_put_contents("C:\AnalyzeTextInvoked.txt", "yeah");
	//file_put_contents("C:\AnalyzeTextInput.txt", $content);
    $result = new stdClass();//array('EntitiesPerson' => "wawi", 'EntitiesOrganization' => "lawi");
    $result->AnalyzeTextResult = new stdClass();



    $delimiter = "";

	//$result->AnalyzeTextResult->PersonName = extractFacebookUser($content);
	//$result->AnalyzeTextResult->PersonFriends = extractFacebookFriends($content, $delimiter);
	//return $result;
    if (true)//strpos($content,"IntuView", 0) === 0)
    {
	    $arr = analayzeFile($mysqli, $content, "tmp.txt");
	file_put_contents("C:\arrmsg.xml", $arr[msg]);
try{
	    $xml = new SimpleXMLElement(utf8_encode($arr[msg]));
} catch (Exception $e) {
	$result->AnalyzeTextResult->EntitiesOrganization = isXML($arr[msg]);
	$result->AnalyzeTextResult->EntitiesPerson = $e->getMessage();
	return $result;
}

	    //
	    $aggRDF = $xml->xpath('/IVEnvelope/Notification/AnalyzeFile/OutputParameters/FileTriples/AggregatedRDF');
	    $digestRDF = $xml->xpath('/IVEnvelope/Notification/AnalyzeFile/OutputParameters/FileTriples/DigestRDF');
	    
	    while(list( , $node) = each($aggRDF)) {
	    	$aggRDFStr = $node;
	    }
	    
	    
	    $xml = new SimpleXMLElement($aggRDFStr);
	    
	    
	    
	    while(list( , $node) = each($digestRDF)) {
	    	$digestRDFStr = $node;
	    }
	    $digestXml = new SimpleXMLElement($digestRDFStr);
	     
	    $persons = $xml->xpath('/rdf:RDF/rdf:Description[iv:entity-type/@rdf:resource="http://www.intuview.com/ontology#Person-object"]/iv:caption[@xml:lang="en"]');
    	while(list( , $node) = each($persons)) {
    		$node = removeBrackets($node);
    		appendValue($result->AnalyzeTextResult->EntitiesPerson, $node, $delimiter, true);
	    }

        $organization = $xml->xpath('/rdf:RDF/rdf:Description[iv:entity-type/@rdf:resource="http://www.intuview.com/ontology#Organizational-identity"]/iv:caption[@xml:lang="en"]');
    	while(list( , $node) = each($organization)) {
	    	appendValue($result->AnalyzeTextResult->EntitiesOrganization, $node, $delimiter, true);
    	}
    
        $places = $xml->xpath('/rdf:RDF/rdf:Description[iv:entity-type/@rdf:resource="http://www.intuview.com/ontology#Place-object"]/iv:caption[@xml:lang="en"]');
    	while(list( , $node) = each($places)) {
	    	appendValue($result->AnalyzeTextResult->EntitiesPlace, $node, $delimiter, true);
	    }

	    $entitiesPositive = $xml->xpath('/rdf:RDF/rdf:Description[iv:sentiment/@rdf:resource="http://www.intuview.com/ontology#pro"]/iv:caption[@xml:lang="en"]');
	    while(list( , $node) = each($entitiesPositive)) {
	    	appendValue($result->AnalyzeTextResult->EntitiesPositive, $node, $delimiter, false);
	    }
	     
    	$entitiesNegative = $xml->xpath('/rdf:RDF/rdf:Description[iv:sentiment/@rdf:resource="http://www.intuview.com/ontology#anti"]/iv:caption[@xml:lang="en"]');
	    while(list( , $node) = each($entitiesNegative)) {
	    	appendValue($result->AnalyzeTextResult->EntitiesNegative, $node, $delimiter, false);
	    }
	    $result->AnalyzeTextResult->DocumentSentiment = count($entitiesPositive) - count($entitiesNegative);

	    //fill relation between person and his organization
	    $personsOrganizations = $xml->xpath('/rdf:RDF/rdf:Description[iv:entity-type/@rdf:resource="http://www.intuview.com/ontology#Person-object" and iv:organization and iv:caption/@xml:lang="en"]');
	    while(list( , $node) = each($personsOrganizations)) {
			$ordId = $node->xpath('iv:organization/@rdf:resource');
   			//since the organization id is not aggregated (bug in IntuScan) - need to extract organization name from non-aggregated digest xml
  			$orgName = $digestXml->xpath('/rdf:RDF/rdf:Description[@rdf:about="' . $ordId[0] . '"]/iv:caption[@xml:lang="en"]');
  			$orgName = $orgName[0];
  			//support only one organization for now
   			if ($result->AnalyzeTextResult->OrganizationRelation == null)
 				$result->AnalyzeTextResult->OrganizationRelation = $orgName;
  			else if (strcmp($result->AnalyzeTextResult->OrganizationRelation, $orgName) != 0)
  				continue;
  			
			//concatenate person of organization
			$person = $node->xpath('iv:caption[@xml:lang="en"]');
			$person = removeBrackets($person[0]);
			appendValue($result->AnalyzeTextResult->OrganizationPersons, $person, $delimiter, true);
	    }

	    //relations
	    $relations = $digestXml->xpath('/rdf:RDF/rdf:Description[iv:relationship-type]');
	    while(list( , $node) = each($relations)) {
	    	$personId1 = $node->xpath('iv:subject-entity/@rdf:resource');
  			$personName1 = $digestXml->xpath('/rdf:RDF/rdf:Description[@rdf:about="' . $personId1[0] . '"]/iv:caption[@xml:lang="en"]');
  			$personName1 = removeBrackets($personName1[0]);
 			//support only one related for now
   			if ($result->AnalyzeTextResult->FamilyRelated == null)
 				$result->AnalyzeTextResult->FamilyRelated = $personName1;
  			else if ($result->AnalyzeTextResult->FamilyRelated != null && $result->AnalyzeTextResult->FamilyRelated != $personName1)
  				continue;

  			$personId2 = $node->xpath('iv:object-entity/@rdf:resource');
  			$personName2 = $digestXml->xpath('/rdf:RDF/rdf:Description[@rdf:about="' . $personId2[0] . '"]/iv:caption[@xml:lang="en"]');
  			$personName2 = removeBrackets($personName2[0]);
  			appendValue($result->AnalyzeTextResult->FamilyRelatives, $personName2, $delimiter, true);
	    }
    }
    //else
    //	$result->AnalyzeTextResult->EntitiesPerson = "iv person";//"a " . $content . " world!";
    	   
    return $result;
}

function AnalyzeFileAsRDF($mysqli, $request)
{
    $intuscanHost = getSystemSettingsProp($mysqli, "intuscanHost");
    $intuscanPort = getSystemSettingsProp($mysqli, "intuscanPort"); 
	
	$response = new stdClass();
	try{
		$content = $request->Request->text;
		$fileName = $request->Request->fileName;
		if ($fileName == null)
			$fileName = "tmp.txt";
		$id = $request->Request->id;
		$username = $request->Request->username;
		$password = $request->Request->password;
		if ($username != "Samsung" || $password != "5g@#sNST^aNsd")
			return array(Error=>"unauthorized user $username and password $password");
		
		if (!$id) $id = 1;
		$arr = analayzeFile($mysqli, $content, $fileName, $username, null, null,  $id);
		file_put_contents("C:/arr.xml", print_r($arr, true));
		if (!is_array($arr) || !array_key_exists("msg", $arr))
			$response->Error = $arr;
		else
		$response->Result = utf8_encode($arr[msg]);
	}
	catch (Exception $e){
		return $response->Error = $e->getMessage();
	}
	file_put_contents("C:/response.xml", print_r($response, true));
	return $response;
}

/*$request = new stdClass();
$request->Request = new stdClass();
$request->Request->text = "hello, I'm going. I don't want you to excort me further.";
AnalyzeFileAsRDF($request);*/
#echo AnalyzeText("wey")['EntitiesPerson'];
ini_set("soap.wsdl_cache_enabled", "0");
$server = new SoapServer("IntuViewWS.wsdl", array('encoding'=>'UTF-8'));
$server->addFunction("AnalyzeText");
$server->addFunction("AnalyzeFileAsRDF");
$server->handle();
?>