<?php
require("config.inc");

function give_up($mess) {
	header("Location: http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/error.php?mess=$mess");
	exit();
}

function db_connect() {
	$link = @mysql_connect(HOST, USER, PASSWORD );
	if (!$link) give_up("could not connect to the database server");
	$select = @mysql_select_db(DBNAME, $link);
	if (!$select) give_up("could not select the database");
	return $link;
}

function db_query($q) {
	$result = mysql_query($q);
	if (!$result) give_up("a database query ($q) failed");
	return $result;
}

// jde, 15/08/17, added term so we can check if it points to itself
function format_xrefs($id, $term) {
//	$xref_query = "select term from xrefs where id = $id order by term";
	$xref_query = "select term from topic where term like '%$term%'";
	$xref_records = db_query($xref_query);
	$xrefs = "";
	$n = mysql_num_rows($xref_records);
	if ($n > 0) {
		$xrefs = "<div class = \"xrefs\"><h1>See also</h1><ul>";
		for ($i = 0; $i < $n; ++$i) {
			$refa = mysql_fetch_array($xref_records);
			$ref = $refa["term"];
//echo $ref . '!' .$term;			
			if ( strtolower($ref) != strtolower($term) )  // ignore pointing back to self
			   $xrefs .= "<li><a href=\"glossary3.php?term1=$ref\" title = \"look up $ref\">$ref</a></li>";
		}
		$xrefs .= "</ul></div>";
	}
	return $xrefs;
}

function format_definition($term, $definition_array, $i, $n) {
	$q = $n > 1 ? " ($i)": "";
	$def = $definition_array["description"];
	$returnedTerm = $definition_array["term"];
	$xrefs = format_xrefs($definition_array["id"], $returnedTerm);	
	return "<dt>$returnedTerm$q</dt><dd>$def$xrefs</dd>";
}

function do_definition($term, $user, $history) {
	return $term == "" ? "" : get_definition($term, $user, $history);
}

function get_definition($term, $user, $history) {
	$term = mysql_escape_string($term);
	if ( get_CheckBoxValue() == 'Y' )
	   $definition_query = "select id, term, description from topic where term = '$term'";
	else
	   $definition_query = "select id, term, description from topic where term like '%$term%'";
	return extract_definition($term, db_query($definition_query), $user, $history);
}

function extract_definition($term, $definition_records, $user, $history) {
	$n = mysql_num_rows($definition_records);
	if ($n == 0)
	   return "<p>No definition for <strong>$term</strong> was found</p>";
	else {
	   add_to_count($term);
	   add_to_history($term, $user, $history);
	   return make_definitions($term, $definition_records, $n);
	}
}

function make_definitions($term, $definition_records, $n)
{
	$definition = "<dl>";
	for ($i = 1; $i <= $n; ++$i)
	    $definition .= format_definition($term, mysql_fetch_array($definition_records), $i, $n);
	$definition .= "</dl>";
	return $definition;
}

function add_to_count($term) {
	$records = db_query("select * from counts where term='$term'");
	if (mysql_num_rows($records) == 0)
		db_query("insert into counts values('$term', 1)");
	else
		db_query("update counts set count = count + 1 where term='$term'");
}

function set_up() {
	db_connect();
	$user_id = isset( $_COOKIE["userid"] ) ? $_COOKIE["userid"] : "";
	if ($user_id == "") $user_id = uniqid("");
	setcookie("userid", $user_id, time()+30*24*60*60);
	return $user_id;
}

function get_term() {
	$t2 = isset( $_REQUEST['term2'] ) ? $_REQUEST['term2'] : "";
	return $t2 != "" ? $t2 : isset( $_REQUEST['term1'] ) ? $_REQUEST['term1'] : "";
}

// added dev 29th Nov 07
function get_CheckBoxValue()
{
        $cbxv = isset( $_REQUEST['checkboxValue'] ) ? $_REQUEST['checkboxValue'] : "";
 	return trim( $cbxv );
}

function normalize($v, $n1, $n2, $m) {
	return round((($v - $n1 + 1) * $m)/($n2 - $n1 + 1));
}

function make_link($t, $n) {
	return "<a href=\"glossary3.php?term1=$t\" class=\"l$n\" title=\"Look up $t\">$t</a>";
}

function encloud($a) {
	$s = "";
	foreach ($a as $k => $v)
		$s .= make_link($k, $v) . " ";
	return $s;
}

function do_cloud() {
	$records = db_query("select * from counts order by count desc");
	$n = mysql_num_rows($records);
	if ($n > MAXCLOUDSIZE) $n = MAXCLOUDSIZE;
	for ($i = 0; $i < $n; ++$i) {
		$record = mysql_fetch_array($records);
		$counts[$record["term"]] = $record["count"];
	}
	return make_cloud($counts);
}

function make_cloud($counts) {
	$max = reset($counts);
	$min = end($counts);
	foreach ($counts as $k => $v)
		$counts[$k] = normalize($v, $min, $max, 5);
	ksort($counts);
	return encloud($counts);
}

function get_history($user) {
	$query = "select term from histories where user = \"$user\" order by n";
	$records = db_query($query);
	$n = mysql_num_rows($records);
	if ($n == 0) return null;
	for ($i = 0; $i < $n; ++$i) {
		$record = mysql_fetch_array($records);
		$hist[$i] = $record["term"];
	}
	return $hist;
}

function add_to_history($term, $user, $history) {
	db_query("delete from histories where user=\"$user\"");
	db_query("insert into histories values (\"$user\", \"$term\", 0)");
	if ($history != null) {
		$i = 1;
		foreach ($history as $h) {
			if ($h != $term && $i < HISTLEN) {
				db_query("insert into histories values (\"$user\", \"$h\", $i)");
				++$i;
			}
		}
	}
}

function do_recent_searches($history) {
	if ($history == null) return "";
	$s = "<select id=\"term2\" name=\"term2\">";
	$s .= "<option label=\"Recent Searches\" value =\"\" selected=\"selected\">Recent Searches</option>";
	foreach ($history as $h)
		$s .= "<option label=\"$h\" value=\"$h\">$h</option>";
	$s .= "</select>";
	return $s;
}

// Dev added Dec 30th 2007
function random( $n ) {
  srand( time() );
  return rand( 1, $n );
}

function getRandomDefinition( $asXML )
{
        $dbRecords = mysql_query( 'SELECT count(*) FROM `topic`' );  // execute the sql
        $count = mysql_fetch_array($dbRecords);  // get the count return, this is an array of strings
        $n = $count[ 0 ];	// turn the first array field into a number ie the no of records in db

	$recNo = random( $n ); // generate a random number in range 1 -> db record count
//echo $n." ".$recNo;
        $aQuery = "SELECT term, description FROM `topic` WHERE id =" . $recNo;  // set sql to get that record
//echo $aQuery;
        $dbRecords = mysql_query( $aQuery ); // execute the sql command to get the record

	$definition = "";
	$n = mysql_num_rows($dbRecords);
	if ($n == 0) {
		if ( $asXML )
		{
		   return '<?xml version="1.0"?><response><term>No Term</term><definition>No definition was found.</definition></response>';
		}
		else
		{  // assume Text wanted
		   return "<p>No definition for <strong>random value</strong> was found</p>";
		}
        }
	else
	{
	    if ( $asXML ) $definition .= '<?xml version="1.0"?><response>';
		while ($row = mysql_fetch_array($dbRecords))
		{
		  if ( $asXML )
		  {
		    $definition .= "<term>". $row['term']."</term><definition>". $row['description']."</definition>";
		  }
		  else
		  {
		    $definition .= $row['term'].' is '. $row['definition'].'<br/>';
		  }
		}
	    if ( $asXML ) $definition .= "</response>";
	    return $definition;
	}
}

function getRandomQuestion() 
{
	$definition = "<p>If see this <strong>message</strong> something wrong! Check getRandomQuestion() function.</p>";	// setup empty definition to start with
        $dbRecords= mysql_query( 'SELECT count(*) FROM `question`' );  // execute the sql
        if ($dbRecords) {
		$count = mysql_fetch_array($dbRecords);  // get the count return, this is an array of strings
		$n = $count[ 0 ];	// turn it the first array field into a number
		$definition = "";	// setup empty definition to start with
		if ($n == 0)
			return "<p>No question for <strong>random value</strong> was found</p>";
		else 
		{	
			$recNo = random( $n ); 
			//echo $n." ".$recNo;	
			$aQuery = "SELECT question, choicea, choiceb, choicec, choiced FROM `question` WHERE id =" . $recNo;
			//echo $aQuery;	
			$dbRecords = mysql_query( $aQuery );

			$n = mysql_num_rows($dbRecords);
			if ($n == 0)
				return "<p>No definition for <strong>random value</strong> was found</p>";
			else 
			{
				while ($row = mysql_fetch_array($dbRecords))
				{
				  $definition .= '<h1>'.$row['question'].'</h1><br/>'.'<li>'. $row['choicea'].'</li><br/>'.'<li>'. $row['choiceb'].'</li><br/>'.'<li>'. $row['choicec'].'</li><br/>'.'<li>'. $row['choiced'].'</li><br/>';
				}
				$definition .= '<br/><strong>Please choose an option</strong>';			

			}
		}
	}
	return $definition;
}	

