<?php
/*

#####################################################################################
# NIST-developed software is provided by NIST as a public service. You may use, 
# copy and distribute copies of the software in any medium, provided that you 
# keep intact this entire notice. You may improve, modify and create derivative 
# works of the software or any portion of the software, and you may copy and 
# distribute such modifications or works. Modified works should carry a notice 
# stating that you changed the software and should note the date and nature of 
# any such change. Please explicitly acknowledge the National Institute of 
# Standards and Technology as the source of the software.
# 
# NIST-developed software is expressly provided “AS IS.” NIST MAKES NO WARRANTY 
# OF ANY KIND, EXPRESS, IMPLIED, IN FACT OR ARISING BY OPERATION OF LAW, 
# INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS 
# FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT AND DATA ACCURACY. NIST NEITHER 
# REPRESENTS NOR WARRANTS THAT THE OPERATION OF THE SOFTWARE WILL BE 
# UNINTERRUPTED OR ERROR-FREE, OR THAT ANY DEFECTS WILL BE CORRECTED. NIST DOES 
# NOT WARRANT OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF THE SOFTWARE OR 
# THE RESULTS THEREOF, INCLUDING BUT NOT LIMITED TO THE CORRECTNESS, ACCURACY, 
# RELIABILITY, OR USEFULNESS OF THE SOFTWARE.
# 
# You are solely responsible for determining the appropriateness of using and 
# distributing the software and you assume all risks associated with its use, 
# including but not limited to the risks and costs of program errors, compliance 
# with applicable laws, damage to or loss of data, programs or equipment, and the 
# unavailability or interruption of operation. This software is not intended to 
# be used in any situation where a failure could cause risk of injury or damage 
# to property. The software developed by NIST employees is not subject to 
# copyright protection within the United States.
#####################################################################################
Author: Ben Livelsberger
*/

include_once('../include/global.php');
$path = is_ftlogs_mounted(TRUE);
$filename = "ss-config.txt";

// We want toolname and toolversion early so we can use them in the page_h1 and page_breadcrumb. Read
// them in from the ss-config file. It's more convenient to ingest ss-config.txt further down on this 
// page so we can print any error messages w/in the context of the page, but we'll still try to snag 
// these 2 values here...
if (file_exists($path."/".$filename)){ 
	// try to read config file
	$testconfiglines = file($path."/".$filename);
	if ($testconfiglines !== false){ // read of config file was successful!
		// initialize...
		$toolname = "";
		$toolversion = "";
		// get toolname and toolversion from ss-config.txt file
		foreach ($testconfiglines as $line){
			if(strpos($line, "toolname") !== false){
				$line_exploded = explode(" ", trim($line));
				$toolname = implode(" ", array_slice($line_exploded, 1));
			} else if(strpos($line, "toolversion") !== false){
				$line_exploded = explode(" ", trim($line));
				$toolversion = implode(" ", array_slice($line_exploded, 1));
			} 						
		}
	} 
}

$page_title = "SS - Select Search Engine";

// if we have a value for $toolname and $toolversion, use them in the page_h1 and page_breadcrumb
if ($toolname != ""){
	$page_breadcrumb = "Running String Search Tests for ".$toolname." Version ".$toolversion;
} else {
	$page_breadcrumb = "Running String Search Tests";
}

//$page_h1 = "Selecting String Search Engine";
$page_h1 = "Selecting a Search Engine";
include "ft_ss_need_logs.php";
include_once('../include/ss-global.php');

//echo '<h2 style="font-size:1.7em; color:#008000"><b>Select String Search Engine</b><br></h2>';

$continue = 1; // set $continue to true

// we did a check for if the user's FT-LOGS drive was mounted in ft_ss_head.php (via ft_ss_need_logs.php).
if ($ftlogs_mounted != 1) { //  If the drive's not mounted, don't continue.
	$continue = 0;
}

// How did the user get to this page? if they got here from savetestconfigfile, then we need to 
// 1) pull all the search tool and test information from the submitted form and 2) write that info to 
// a config file for safe keeping. If the user got here from some other page, then there should 
// already be a test config file on FT-LOGS; read it in so that we have access to the test/tool info
if ($continue) {
	// when drag and drop file path in linux, path begins with 'file:///', remove!
	//$path = str_replace("file:///", "/", $path);
	//$path = trim_trailing_slash($path);
		
	// does ss-config.txt config file exist?
	if (file_exists($path."/".$filename)){ 
		// try to read config file
		$testconfiglines = file($path."/".$filename);
		if ($testconfiglines !== false){ // read of config file was successful!
			// initialize...
			$engines = array();
			$testcases = array();
			$se_other_name = "";
			// $blockerinfo = get_blocker_info($handle);

			// get toolname and toolversion from hwb-config.txt file
			foreach ($testconfiglines as $line){
				if(strpos($line, "engines") !== false){ 
					$line_exploded = explode(" ", trim($line));
					$engines = array_slice($line_exploded, 1);
				} elseif (strpos($line, "se_other_name") !== false){
					$line_exploded = explode(" ", trim($line));
					$se_other_name = implode(" ", array_slice($line_exploded, 1));
				} elseif(strpos($line, "FT-SS") !== false){
					$line_exploded = explode("-", trim($line));
					// check for a valid test case name... if we explode a proper test 
					// case name, e.g., FT-HWB-pcie, it should have a size of 3
					if ((count($line_exploded) == 3) || (count($line_exploded) == 4) || (count($line_exploded) == 5)){
						// store the significant portion of the test case name, e.g., pcie for FT-HWB-PCIE
						$testcases[] = trim($line);
						//echo "<br>".$line_exploded[2]."<br>";
					} else { // invalid test case name
						echo "<p><b>Error:</b> error encountered parsing ".$path."/".$filename." at ";
						echo  '"'.trim($line).'". Exiting! </p>\n';
						$continue = 0;
					}
				}
			}
		} else { // read of hwb-config.txt failed for some reason
			echo "<p><b>Error:</b> error opening ".$path."/".$filename.".</p>";				
			$continue = 0;
		}
	} else {
		echo "<p><b>Error:</b> no test configuration file (".$filename.") exists on your log drive. ";
		echo "Please use the <a href=\"./writeblocktype.php\">Generate Test Cases &amp; Start ";
		echo "Testing</a> pages to generate the list of tests to run to test your tool (the ";
		echo "test configuration will automatically be saved to your log drive).</p>";			
		$continue = 0;
	}			
}

/* Try to pull back any values for selected_dataset and selected_engine that we might have 
   stored in ss-last.txt */
if ($continue){
	$lastfile = "ss-last.txt";
	// initialize...
	$last_ds = "";
	$last_se = "";
	// depending on where we're coming from in the testing process, ss-last.txt may or may not exist
	if (file_exists($path."/".$lastfile)){ 
		// try to read the last selected dataset and search engine values
		$lastlines = file($path."/".$lastfile);
		if ($lastlines !== false){ // read of config file was successful!
			// get last used dataset and engine from ss-last.txt file
			foreach ($lastlines as $line){
				if(strpos($line, "selected_dataset") !== false){ 
					$line_exploded = explode(" ", trim($line));
					$last_ds = implode(" ", array_slice($line_exploded, 1));
				} else if(strpos($line, "selected_engine") !== false){ 
					$line_exploded = explode(" ", trim($line));
					$last_se = implode(" ", array_slice($line_exploded, 1));
				}	
			}
		} else { // read of ss-last.txt failed for some reason
			echo "<p><b>Error:</b> error opening ".$path."/".$lastfile.".</p>";				
			$continue = 0;
		}
	}
}

// to start, set $selected_* values to $last_* values
$selected_dataset = $last_ds;
$selected_engine = $last_se;

// There are "two" paths that can get us to this page (selectsearchengine): 1) selectdataset.php and 
// 2) "everything else." If #1, save the passed selected_dataset value along with any previously existing 
// selected_engine value to ss-last.txt.
if ((strpos($_SERVER['HTTP_REFERER'], "selectdataset") !== false) && $continue){ // case 1) selectdataset.php
	// grab selected_dataset 
	$selected_dataset = $_POST['selected_dataset'];

	// we need to do a check to see if the user selected a data set on the previous page
//	if ($selected_dataset == "") { // user did not select a data set to test
//		echo "<p><b>Error:&nbsp;</b> <i><b>No data set selected. Please use the browser's back button to return to the previous page and select a data set to test (from 'Pending or Incomplete Data Sets' or 'Completed Data Sets').</b></i></p>";
//		$continue = 0;	
//	} else {
		if (!$handle = fopen($path."/".$lastfile, 'w')){
			echo "<p><b>Error:</b> error encountered trying to open ".$path."/".$lastfile."</p>\n";
			$continue = 0;
		} else {
			// the user got to this page from selectdataset.php; save the user's dataset selection to file
			fwrite($handle, "selected_dataset ".$selected_dataset."\n"); 
			if ($selected_engine){ // if there was a previously selected search engine, do not discard it,
								   // i.e., save it back to ss-last.txt
				fwrite($handle, "selected_engine ".$selected_engine."\n"); 
			}
		}	
	//}
}

// If we haven't run into any errors, print/display the gui/let the user select which search engine
// they will test
if ($continue) { 

		
	echo '<p>Selected data set: <i><b>'.$selected_dataset.'</b></i> (<a href="selectdataset.php">update</a>).&nbsp; </p>';
	
//	echo '&nbsp; Click <a href="selectdataset.php">here</a> to select a different data set.</p>';
//	echo '<p>Click <a href="selectdataset.php">here</a> to select a different data set.</p>';
	
	echo "<p>You've selected to test your tool using ".count($engines)." search engines (<i>";
	if ($engines[0] == "Other"){
		echo $engines[0].' - '.$se_other_name;		
	} else {
		echo $engines[0];
	}
	if (count($engines) == 2) { 
		if ($engines[1] == "Other"){
			echo " &amp; ".$engines[1].' - '.$se_other_name;		
		} else {
			echo " &amp; ".$engines[1];
		}
	} elseif (count($engines) == 3) { 
		if ($engines[2] == "Other"){
			echo ", ".$engines[1]." &amp; ".$engines[2].' - '.$se_other_name;
		} else {
			echo ", ".$engines[1]." &amp; ".$engines[2];
		}
	}
	
	echo "</i>). ";
	echo "<ul><li>Select a search engine from 'Pending or Incomplete Search Engines' and click the ";
	echo "'Select search engine' button to test your tool for that engine.</li><li>You can re-test a search engine by selecting it from ";
	echo "'Completed Search Engines.'</li></ul>";
	
	echo ' </p>';
	echo '<br>';
	echo '<form method="POST" action="ft_ss_select_case.php"> ';

	// initialize...
	$engines_tested = array();
	$engines_pending = array();
	
	foreach ($engines as $engine){ // iterate over all the SEs the user wants to test
		// we'll need the path to where the results for $engine's tests should be stored
		if ($engine == "Other"){ // if the user selected "Other", append the name they provided
			$base = $path.'/'.$engine."_".$se_other_name.'/'.$selected_dataset;
		} else {
			$base = $path . '/' . $engine . '/' . $selected_dataset;
		}
		
		if (is_se_tested($selected_dataset, $engine, $base, $testcases)){
			// case: all tests have been run for this se
			$engines_tested[] = $engine;
		} else {
			// case: some cases still need to be run for this se
			$engines_pending[] = $engine;
		}
	}

	$first = TRUE;
	
//	echo '<h2 style="color:#008000 ">Pending or Incomplete Test Cases</h2>';
	echo '<h2 style="color:#008000 ">Pending or Incomplete Search Engines</h2>';
 	if ( count($engines_pending) > 0 ) {
		// if there are some test cases pending, print them here in a table
		//echo "<table class=\"bordered_table2\">";
		echo "<table class=\"bordered_table2\" style=\"width: 38%;\">\n";
		// print table headings
//		echo '<tr><td colspan="2" style="width: 40%; text-align: left;"><b>Search Engine</b></th></tr>';
		echo '<tr><td colspan="2" style="text-align: left;"><b>Search Engine</b></th></tr>';
		// print each table row
		foreach ($engines_pending as $engine) {
			echo '<tr><td style="width: 5%; text-align: center;"><input name="selected_engine" value="'.$engine.'" type="radio" required';			
			// we want to autoselect a search engine for the user, but we may use one of two metrics for making the choice 
			if ($last_se && in_array($last_se, $engines_pending)){ // if there is a se that was previously selected and we've yet to finish testing it...
				if ($engine == $last_se){
					echo ' checked="checked"';
				}
			} else {
				// no previously selected ds
				if ($first){
					echo ' checked="checked"';
					$first = FALSE;
				}
			}			
			echo '></td>'; // radio button
			if ($engine == "Other"){ // if the engine type is Other, then we need to print out the "Other" search engine's name
				echo "<td>&nbsp;".$engines_dict[$engine]." - ".$se_other_name."</td>"; // test case name					
			} else {
				echo "<td>&nbsp;".$engines_dict[$engine]."</td>"; // test case name					
			}
			echo "</tr>"; // brief test case description
		}
		echo "</table>";
		echo '<br>';
	} else {
		// no test cases pending
		echo "<p>&nbsp;&nbsp;&nbsp;<i>None</i></p>";
	}	
	
    // button to take us to the next page
	echo "	<input value=\" Select search engine \" type=\"submit\"><br><br>";
	
//	echo '<h2 style="color:#008000">Completed Test Cases</h2>';
	echo '<h2 style="color:#008000 ">Completed Search Engines</h2>';
	
	if ( count($engines_tested) > 0 ){			
	    // if there are some completed test cases, print them here in a table
	    echo "<table class=\"bordered_table2\" style=\"width: 38%;\">\n";
	    // print table headings
//	    echo '<tr><td colspan="2" style="width: 40%; text-align: left;"><b>Search Engine</b></th></tr>';
	    echo '<tr><td colspan="2" style="text-align: left;"><b>Search Engine</b></th></tr>';
		// print each table row
	    foreach ($engines_tested as $engine) {
			echo '<tr><td style="width: 5%; text-align: center;"><input name="selected_engine" value="'.$engine.'" type="radio" required></td>'; // radio button
			echo "<td>&nbsp;".$engines_dict[$engine]."</td>"; // test case name
			echo "</tr>"; // brief test case description	    }
		}
	    echo "</table>";
		echo "<br>";
	} else {
          // no completed test cases
	  echo "<p>&nbsp;&nbsp;&nbsp;<i>None</i></p>";
	}

	// pass along the values we have for toolname and toolversion so that we have them upfront on the next page

?>	

</form>
</p>

<?php
/*
*/
//include "ft_ss_home_links.php";
?>
<?php
}  // endif($ftlogs_mounted==1)
include "ft_ss_tail.php";
?>

