<?php
// ***********************************************
// couchDB php Library: https://github.com/dready92/PHP-on-Couch
// ***********************************************
require_once "../lib/couch.php";
require_once "../lib/couchClient.php";
require_once "../lib/couchDocument.php";

// ***********************************************
// resizing images to cache: https://github.com/wes/phpimageresize
// resp.: http://joedesigns.com/v22/?page=scripts_widgets&id=67
// ***********************************************
//include 'function.resize.php';

// the html Container for the non computed stuff of the website
require_once "htmlContainer.php";


if(isset($_GET["q"])) // 
{
	$solr = new CSolrResult(str_replace(" ", "+", $_GET["q"]));
}

function h($s)
{
	return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

function u($s)
{
	return rawurlencode($s);
}

class CSolrResult
{
	var $query, $result, $results, $numberResults, $htmlContainer, $client, $start, $intervall, $refine;
	
	function CSolrResult($query)
	{
		$this->query = $query;
		// ***************************************
		// start of query and intervall size
		// ***************************************
		$this->start	  = 0;
		$this->intervall  = 20;
		$this->refine	  = "";
		
		$hightlight 	  = "+highlighting";
		$content		  = "attr_content";
		
		if(isset($_GET["start"])) // 
		{
			$this->start = $_GET["start"];
		}
		
		// refine to one record
		if(isset($_GET["refine"])) // 
		{
			$this->refine = "&fq=attr_stream_source_info%3A" . $_GET["refine"];
			$this->start	  = 0;
			$this->intervall  = 1000;
		}
		
		// only commentaries
		if(isset($_GET["commentary"])) // 
		{
			$this->refine = "&fq=id%3Acommentary*";
		}
		
		// nondetailed list of records/commentaries
		if(isset($_GET["list"])) // 
		{
			$this->start	  = 0;
			$this->intervall  = 1000;
			$hightlight		  = "";
			$content		  = "";
		}
		
		// ***************************************
		// create instance of the htmlContainer class
		// ***************************************
		$this->htmlContainer = new CHtmlContainer;
		
		// ***************************************
		// create database client (db query per id in processResults)
		// ***************************************
		$this->client = new couchClient ('http://localhost:5984','cam');
		
		// ***************************************
		// solr query and results
		// ***************************************
				  //http://localhost:8983/solr/select?indent=on&version=2.2&q=attr_content%3Alondon&fq=&start=0&rows=1000&fl=attr_stream_source_info&qt=&wt=json&explainOther=&hl.fl=
		$query = "http://localhost:8983/solr/cam/select?indent=on&version=2.2&q=attr_content%3A" . $this->query . $this->refine . "&start=" . $this->start . "&rows=" . $this->intervall . "&fl=id%2Cattr_stream_name%2C" . $hightlight . "&qt=&wt=json&explainOther=&hl=on&hl.fl=" . $content;
		//echo $query;

$this->result = $this->curlData($query);
		$this->result = json_decode($this->result);
		$this->result = $this->objectToArray($this->result);
		
		$this->displayResults();
	}
	
	// ************************************************
	//
	// ************************************************
	function nextPage()
	{
		$commentary = "";
		if(isset($_GET["commentary"]))
			$commentary = "&commentary";
		for($start=0, $i=1; $start <  $this->numberResults; $start += ($this->intervall), $i++)
		{
			if($start == $this->start)
				echo '<b>' . $i . '</b> ';
			else
				echo '<a href=\'showSolrResults.php?q=' . $this->query . '&start=' . $start . $commentary . '\'>' . $i . '</a> ';
		}
	}
	
	// ************************************************
	//
	// ************************************************
	function requestDatabase($id)
	{
		$doc = array();
		
		// ***************************************
		// commentaries don't have titles right now
		// ***************************************
		if(strstr($id, "commentary") != false)
			$id = str_replace("commentary", "record", $id);
			
		
		// ***************************************
		// first fetch document: representation
		// ***************************************
		try 
		{
   			$doc = $this->client->asCouchDocuments()->asArray()->getDoc($id);
		}
		catch (Exception $e) 
   		{
   			echo "something weird happened: ".$e->getMessage()."<BR>\n";
		}
		
		// ***************************************
		// get title from result array
		// ***************************************
		return ($doc["Year"][0] . ': ' . $doc["Short_Title"][0]);
	}
	
	// ************************************************
	//
	// ************************************************
	function displayResults()
	{
		$this->htmlContainer->htmlHeader("Primary Sources on Copyright - Search Results");
		echo '<div class="container">';
		$this->htmlContainer->htmlContainer();

		echo '<div id="record" class="right">';
		
		echo '<span class="p3">';
	
		// **************
		// headline
		// **************
		// normal search
		if(!isset($_GET["refine"]))
		{
			echo '<span class="p0">';
			echo 'Fulltext search on ' . h($_GET["q"]) . '<br><br>';
			echo '</span>';
		
			echo 'These are the results of a fulltext search within the records translation and transcription.'
					. ' The full text of the commentaries is searched as well.<br><br>';
		}
		// refined search
		else
		{
			echo '<span class="p0">';
			echo 'Refined fulltext search on ' . h($_GET["q"]) . ' within <br>';
			echo $this->requestDatabase("record_" . $_GET["refine"]) . '<br><br>';
			echo '</span>';
		}
		
		// **************
		// nav bar: top
		// **************
		$this->numberResults = $this->result["response"]["numFound"];
		if($this->numberResults == 0)
			$this->numberResults = "No";
		// *
		echo '<a href="javascript:history.go(-1)">Back</a>';
		// *
		if(!isset($_GET["refine"]))
		{
			if(!isset($_GET["list"]))
			{
				echo ' | ' . $this->numberResults . " single results for <em>" . h($_GET["q"]) . '</em>';
				
				// from / to: kind of redundant
				/*
				$end = $this->intervall+$this->start;
				if($end > $this->numberResults)
					$end = $end - ($end - $this->numberResults);
				echo ' | ' . $this->start . ' to ' . $end;
				*/
				
				if(isset($_GET["commentary"]))
				{
					echo ' | <a href=\'showSolrResults.php?q=' . $this->query . '\'>';
					echo "all results";
					echo '</a>';
				}
				else
				{
					echo ' | <a href=\'showSolrResults.php?q=' . $this->query . '&commentary\'>';
					echo "commentaries only";
					echo '</a>';
				}
				
				echo ' | <a href=\'showSolrResults.php?q=' . $this->query . '&list\'>less details</a>'; 
							
				echo '<hr>';
				$this->nextPage();
			}
			else
			{
				echo ' | <a href=\'showSolrResults.php?q=' . $this->query . '\'>more details</a>'; 
			}
		}
		echo "<hr><br>";
		
		// **************
		// results
		// **************
		if($this->numberResults != 0)
		{
			$this->processResults();
		}
		
		// **************
		// footer
		// **************
		echo '</span>';
		echo '</div>';
		$this->htmlContainer->footer();
		echo '</div>';
	}
	
	// ************************************************
	//
	// ************************************************
	function processResults()
	{
		foreach($this->result["response"]["docs"] as $r)
		{
			$this->results[$r["id"]] = array();
			$this->results[$r["id"]]["attr_stream_name"] = $r["attr_stream_name"][0];
		}
	
		foreach(array_keys($this->result["highlighting"]) as $key)
		{
			if(isset($this->result["highlighting"][$key]["attr_content"][0]))
				$this->results[$key]["attr_content"] = $this->cleanText($this->result["highlighting"][$key]["attr_content"][0]);
			else
				$this->results[$key]["attr_content"] = "";
		}
	
		// if refined: put results in array
		if(isset($_GET["refine"]) || isset($_GET["list"]))
			$results = array();
			
		foreach(array_keys($this->results) as $key)
		{
			$dbRequest	= "";
			$link		= "";
			$tmpId		= "";
			
			// record resp. representation
			if(strstr($key, "commentary") == false)
			{
				$tmpFirstUnderscore = strpos($key, "_")+1; // difference between s_123_ and uk_123_
				$tmpFile = str_replace(substr($key, strpos($key, "_", $tmpFirstUnderscore)), "", $key);
				
				$tmpPage = str_replace("_st", "", $key);
				
				// *************************
				// get chapter and page out of string to  request correct page in representation
				// *************************
				// init
				$tmpChapter = $tmpPage;
				// get last _123
				$tmpPage = substr($tmpPage, strrpos($tmpPage, "_"));
				// substract _123 from string: uk_123_x_1
				$tmpChapter = substr($tmpChapter, 0, strrpos($tmpChapter, "_"));
				// get last _: chapter
				$tmpChapter = substr($tmpChapter, strrpos($tmpChapter, "_")+1);
				// put al back into tmpPage
				$tmpPage = $tmpChapter . $tmpPage;
				
				$tmpKind = "translation";
				if(strstr($key, "_transc_") != false)
					$tmpKind = "transcription";
				
				$tmpId = "record_" . $tmpFile;
				
				$link = "http://" . $_SERVER['SERVER_NAME'] . "/cam/tools/request/showRepresentation?id=representation_" . $tmpFile . "&pagenumber=" . $tmpPage . "&show=all"; // before: intval($tmpPage)
				
				// list all results
				if(!isset($_GET["refine"]))
				{
					// detailed result list
					if(!isset($_GET["list"]))
					{
						// form for page is chapter_page:
						$tmpChapter = substr($tmpPage, 0, strpos($tmpPage, "_"));
						$tmpPage	= substr($tmpPage, strpos($tmpPage, "_")+1);
						
						//echo ucfirst($tmpKind) . " of: <b>" . $this->requestDatabase($tmpId) . "</b> (page " . intval($tmpPage) . ")<br>"; 
						echo '<a href="' . $link . '">' . $this->requestDatabase($tmpId) . "</a> (chapter: " . $tmpChapter . ", page: " . $tmpPage . ")<br>"; 
						echo "<i>... " . $this->results[$key]["attr_content"] . " ...</i><br>";
					
						// refine search link
						$query = 'showSolrResults.php?q=' . u($_GET["q"]) . '&refine=' . $tmpFile;
						echo '<a href=\'' . $query . '\'>';
						echo 'show results for this record only';
						echo '</a><br>';
					
						echo '<hr>';
					}
					// list per record
					else
					{
						if(!isset($results[$tmpId]))
						{
							$results["records"][$tmpId] = substr($tmpId, strrpos($tmpId, "_")+1);
							/*
							$results["records"][$tmpId] = array();
							$results["records"][$tmpId]["file"] = $tmpId;
							$results["records"][$tmpId]["year"] = substr($tmpId, strrpos($tmpId, "_")+1);
							*/
						}
					}
				}
				// list refined results
				else
				{
					if(!isset($results[$tmpKind]))
						$results[$tmpKind] = array();
					
					$results[$tmpKind][$tmpPage] = array();
					$results[$tmpKind][$tmpPage]["key"]			= $key;
					$results[$tmpKind][$tmpPage]["id"]			= $tmpId;
					$results[$tmpKind][$tmpPage]["link"]		= $link;
					$results[$tmpKind][$tmpPage]["highlight"] 	= $this->results[$key]["attr_content"];
				}
			}
			// commentary
			else if(strstr($key, "commentary") != false && (!isset($_GET["refine"])))
			{
				if(isset($_GET["list"]))
				{
					if(!isset($results[$key]))
						{
							$results["commentaries"][$key] = substr($key, strrpos($key, "_")+1);
							/*
							$results["commentaries"][$key] = array();
							$results["commentaries"][$key]["file"] = "";
							$results["commentaries"][$key]["year"] = substr($key, strrpos($key, "_")+1);
							*/
						}
				}
				else
				{
					$tmpId = $key;
					$link = "showRecord?id=" . $key;
					echo "<a href=" . $link . ">Commentary</a> on <b>" . $this->requestDatabase($tmpId) . "</b>";
				
					// link to (main) related record
					$tmp = str_replace("commentary", "record", $key);
					$link = "showRecord?id=" . $tmp;
				
					echo " (or <a href=" . $link . ">go to related record</a>)<br>"; //str_replace("commentary_", "", $key) . ": ";
					echo "<i>... " . $this->results[$key]["attr_content"] . " ...</i><br>";
					echo '<hr>';
				}
			}
		}
		
		// ***************************
		// Display results as list of records / no details
		// ***************************
		if(isset($_GET["list"]))
		{
			foreach(array_keys($results) as $kind)
			{
				asort($results[$kind]);
				echo "<b>" . sizeof($results[$kind]) . " " . $kind . " for query on " . h($_GET["q"]) . "</b><br><br>";
				
				foreach(array_keys($results[$kind]) as $key)
				{
					if($kind == "records")
						echo '<a href=\'showSolrResults.php?q=' . $this->query . '&refine=' . str_replace("record_", "", $key) . '\'>';
					else
						echo '<a href=\'showRecord?id=' . $key . '\'>';
					echo $this->requestDatabase($key);
					echo '</a><br>';
				}
				
				echo "<br><br>";
			}
		}
		
		// ***************************
		// Display results for refined search
		// ***************************
		if(isset($_GET["refine"]))
		{
			echo "Go to record ";
			echo "<a href='showRecord?id=record_" . u($_GET["refine"]) . "'>";
			echo $this->requestDatabase("record_" . $_GET["refine"]);
			echo "</a><br><br>";
			
			foreach(array_keys($results) as $keyKind)
			{
				//natsort($results[$keyKind]);
				
				// pageNumber form: chapter_page doesn't sort properly -> create own sorting
				// make an array of chapters, each containg a page -> then sort each chapter
				$tmpSort = array();
				foreach(array_keys($results[$keyKind]) as $pageNumber)
				{
					$tmpChapter = substr($pageNumber, 0, strpos($pageNumber, "_"));
					$tmpPage	= substr($pageNumber, strpos($pageNumber, "_")+1);
					
					if(!isset($tmpSort[$tmpChapter]))
					{
						$tmpSort[$tmpChapter] = array();
					}
					array_push($tmpSort[$tmpChapter], intval($tmpPage));
				}
				
				
				foreach(array_keys($tmpSort) as $chapter)
				{
					natsort($tmpSort[$chapter]);
				}
				
				
				echo '<b>';
				echo sizeof($results[$keyKind]) . " pages found in " . $keyKind;
				echo '</b><br><br>';
				
				
				foreach(array_keys($tmpSort) as $chapter)
				{
					foreach($tmpSort[$chapter] as $page)
					{
						$pageNumber = $chapter . "_" . $page;
						
						// form for page is chapter_page:
						$tmpChapter = substr($pageNumber, 0, strpos($pageNumber, "_"));
						$tmpPage	= substr($pageNumber, strpos($pageNumber, "_")+1);
					
						echo '<a href="' . $results[$keyKind][$pageNumber]["link"] . '">'; 
						echo "Chapter " . $tmpChapter . ", Page " . $tmpPage;
						echo "</a>: ";
						echo "... " . $results[$keyKind][$pageNumber]["highlight"] . " ...<br><hr>";

					}
				}
				
				/*
				foreach(array_keys($results[$keyKind]) as $pageNumber)
				{
					// form for page is chapter_page:
					$tmpChapter = substr($pageNumber, 0, strpos($pageNumber, "_"));
					$tmpPage	= substr($pageNumber, strpos($pageNumber, "_")+1);
						
					echo '<a href="' . $results[$keyKind][$pageNumber]["link"] . '">'; 
					echo "Chapter " . $tmpChapter . ", Page " . $tmpPage;
					echo "</a>: ";
					
					echo "... " . $results[$keyKind][$pageNumber]["highlight"] . " ...<br><hr>";
				}*/
				echo "<br><br>";
			}
		}
	}
	
	
	
	
	// ************************************************
	//
	// ************************************************
	function cleanText($text)
	{
		$text = str_replace("\n", "", $text);
		$text = str_replace("\r", "", $text);
		$text = str_replace("<br>", "", $text);
		$text = str_replace("<em>", "<b>", $text);
		$text = str_replace("</em>", "</b>", $text);
		$text = str_replace("<center>", " ", $text);
		$text = str_replace("</center>", " ", $text);
		$text = str_replace("<p>", " ", $text);
		$text = str_replace("</p>", " ", $text);
		$text = str_replace("<strong>", " ", $text);
		$text = str_replace("</strong>", " ", $text);
		$text = str_replace("<b>", " ", $text);
		$text = str_replace("</b>", " ", $text);
		$text = str_replace("<br />", " ", $text);
		$text = str_replace("<br/>", " ", $text);
		$text = str_replace("<p", " ", $text);
		$text = str_replace("<center", " ", $text);
		$text = str_replace("<strong", " ", $text);
		$text = str_replace("</p", " ", $text);
		$text = str_replace("<blockquote>", " ", $text);
		$text = str_replace("</blockquote>", " ", $text);
		$text = str_replace('<a name="_ednref2" href="#_edn2', " ", $text);
		
		return $text;
	}

	// ************************************************
	//
	// ************************************************
	function objectToArray($object) 
	{ 
		$array = array();
		
    	if (is_object ( $object ) == true) 
    		settype ( $object, "array" ); 
    	
    	foreach ($object as $key => $value) 
    	{ 
    	    if ((is_array($value) == true) or (is_object($value) == true)) 
    	    	$array[$key] = $this->objectToArray($value); 
    	    else 
    	    	$array[$key] = utf8_decode($value); 
    	} 
    	return $array; 
	} 

	// ************************************************
	//
	// ************************************************
	function curlData($path)
	{
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, $path);

        curl_setopt($ch, CURLOPT_TIMEOUT, 180);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $datastring = curl_exec($ch);
        
        curl_close($ch); 
        
        return $datastring;
	}
}



	/*
	$query = "http://localhost:8983/solr/select?indent=on&version=2.2&q=attr_content%3A" . u($_GET["q"]) . "&fq=&start=0&rows=1000&fl=id%2Cattr_stream_name%2C+highlighting&qt=&wt=json&explainOther=&hl=on&hl.fl=attr_content";
	$result = holeDaten($query);
	$result = json_decode($result);
	$result = buildarray($result);
	
	echo "<pre>";
	var_dump($result);
	echo "</pre>";
	
	$results = array();
	
	$numberResults = $result["response"]["numFound"];
	
	if($numberResults == 0)
	{
		echo "No results found for " . h($_GET["q"]) . "<br>";
	}
	
	echo $numberResults . " results for <em>" . h($_GET["q"]) . "</em><br><br>";
	
	foreach($result["response"]["docs"] as $r)
	{
		//echo $r["id"] . " " . $r["attr_stream_name"][0] . "<br>";
		$results[$r["id"]] = array();
		$results[$r["id"]]["attr_stream_name"] = $r["attr_stream_name"][0];
	}
	
	foreach(array_keys($result["highlighting"]) as $key)
	{
		//echo "#" . $key . " " . $result["highlighting"][$key]["attr_content"][0] . "<br>";
		$results[$key]["attr_content"] = cleanText($result["highlighting"][$key]["attr_content"][0]);
	}
	
	foreach(array_keys($results) as $key)
	{
		$link = "";
		//echo $key . "<br>" . $results[$key]["attr_stream_name"] . "<br>" . $results[$key]["attr_content"]. "<br>";
		if(strstr($key, "commentary") == false)
		{
			$tmpFile = str_replace(substr($key, strpos($key, "_", 2)), "", $key);
			$tmpPage = substr($key, strrpos($key, "_")+1);
			$tmpKind = "translation";
			if(strstr($tmpKind, "_transc_") != false)
				$tmpKind = "transcription";
			
			$link = "../request/showRepresentation?id=representation_" . $tmpFile . "&pagenumber=1&show=" . $tmpKind . "#" . $tmpPage;
			echo $tmpKind . " of record " . str_replace("representation", "", $tmpFile) . "<br>"; 
		}
		else
		{
			echo "commentary on " . str_replace("commentary_", "", $key) . "<br>";
			$link = "../request/showRecord?id=" . $key;
		}
			
		echo "... " . $results[$key]["attr_content"] . " ...<br>";
		echo "<a href=" . $link . ">go to result</a><br><br>";
	}


	// ************************************************
	//
	// ************************************************
	function cleanText($text)
	{
		$text = str_replace("\n", "", $text);
		$text = str_replace("\r", "", $text);
		$text = str_replace("<br>", "", $text);
		$text = str_replace("<em>", "<b>", $text);
		$text = str_replace("</em>", "</b>", $text);
		$text = str_replace("<center>", " ", $text);
		$text = str_replace("</center>", " ", $text);
		$text = str_replace("<p>", " ", $text);
		$text = str_replace("</p>", " ", $text);
		$text = str_replace("<strong>", " ", $text);
		$text = str_replace("</strong>", " ", $text);
		$text = str_replace("<br />", " ", $text);
		$text = str_replace("<br/>", " ", $text);
	
		return $text;
	}

	// ************************************************
	//
	// ************************************************
	function buildarray($object) 
	{ 
    if (is_object ( $object ) == true) 
    { 
        settype ( $object, "array" ); 
    } 
    foreach ($object as $key => $value) { 
        if ((is_array ( $value ) == true) or (is_object ( $value ) == true)) 
        { 
            $array [$key] = buildarray ( $value ); 
        } 
        else 
        { 
            $array [$key] = utf8_decode ( $value ); 
        } 
    } 
    return $array; 
	} 

	// ************************************************
	//
	// ************************************************
	function holeDaten($datenPfad)
	{
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, $datenPfad);

        curl_setopt($ch, CURLOPT_TIMEOUT, 180);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $tmpDaten = curl_exec($ch);
        
        curl_close($ch); 
        
        return $tmpDaten;
	}
*/
?>
