<?

/* WIKIPEDIA CONTENT */
global $wikipediaDocument;
$wikipediaDocument = new DomDocument();
function loadWikipediaXml($requestedTerm) {
	// echo $requestedTerm;
	global $wikipediaDocument ;
	$wikipediaHtml;
	
	// set xml url
	$wikipediaDocumentUrl = "http://en.wikipedia.org/w/api.php?action=parse&prop=text&page=".$requestedTerm."&format=xml";
	$CurlData = array( "url" => $wikipediaDocumentUrl,"ua" => $_SERVER['HTTP_USER_AGENT']);

	// load xml
	$wikipediaDocument->loadXML(curl_get_contents($CurlData));

	// get title
	// $title = $wikipediaDocument->getElementsByTagName("caption");

	// get content
	$text = $wikipediaDocument->getElementsByTagName("text");

	// load <text> tag into text array
	$textArray = array();
	foreach ($text as $textTag) {
		array_push($textArray, $textTag->nodeValue);
	}

	// if the first text array is not empty
	if($textArray[0]){
	
		// text array populated!, create new dom doc to look for REDIRECT if any
		$sourceHtmlDom = new domDocument;
		$sourceHtmlDom->loadHTML($textArray[0]);
		$sourceHtmlDom->preserveWhiteSpace = false;
		
		// get documents <ol> and <a>
		$lists = $sourceHtmlDom->getElementsByTagName('ol');
		$links = $sourceHtmlDom->getElementsByTagName('a');
		
		// create an array with <ol>
		$listArray = array();
		foreach ($lists as $value)
		{	
			array_push($listArray, $value->nodeValue);
		}
		// create an array with <a>
		$linkArray = array();
		foreach ($links as $value)
		{	
			array_push($linkArray, $value->nodeValue);
		}
		
		// if "REDIRECT" is found, get the correct term and load document again, if not, echo the contents
		if (preg_match("/REDIRECT.*/i", $listArray[0])) {
			$query_term = $linkArray[0]; 
			// echo "Redirect was found to: ".$linkArray[0].', loading... ';
			loadWikipediaXml(urlencode($linkArray[0]));
		} else {	
			
			// strip <a> tags from html
			$pattern = array("/<a[^<]+?>/", "/<[^<]+?a>/");
			echo preg_replace($pattern, '', $textArray[0]);
			
			//echo $textArray[0];
		}
			
	} else {
		// error, empty return
		echo '<p>We\'re sorry, a server error occurred. Please try again.</p>';	
	}

}


?>