<?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);
$filenamestem = "ss-config";
$filename = $filenamestem.".txt";

// We want toolname and toolversion early so we can use them in the page_h1 and page_breadcrumb. Either 1) read
// them in from a config file or 2) gather them from POST data
if (strpos($_SERVER['HTTP_REFERER'], "savetestconfigfile") === false){ // If we're not coming from savetestconfigfile.php,
	// then we'll need to read these values in from the ss-config.txt 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));
				} 						
			}
		} 
	}
} else { // we're comming from savetestconfigfile.php, so we can gettoolname and toolversion from the POST data
	$toolname = $_POST['toolname'];
	$toolversion = $_POST['toolversion'];
}

$page_title = "SS - Select Data Set";

// 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;
//	$page_h1 = "Selecting String Search Data Set";	
	$page_h1 = "Selecting a Data Set";	
} else {
	$page_breadcrumb = "Running String Search Tests";
//	$page_h1 = "Selecting String Search Data Set";
	$page_h1 = "Selecting a Data Set";	
}

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 Data Set</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) {

	// array to store our list of test cases
	$testcases = array();

	// There are "two" paths that can get us here (selectdataset): 1) savetestconfigfile and 
	// 2) "everything else." If #1, use the passed form variables to write the ss-config.txt
	// to our path (/tmp on dev, /media/FT-LOGS). If #2, use our path to read a previously created 
	// ss-config.txt.
	if (strpos($_SERVER['HTTP_REFERER'], "savetestconfigfile") !== false){ // case 1) savetestconfigfile.php
		//echo "<br><br>referrer: savetestconfigfile.php<br>";

		// Read in the form variables from savetestconfigfile.php.
		// simple string variables
		$se_other_name = $_POST['se_other_name'];
		// array/multivalue variables
		$engines = $_POST['engines'];
		$datasets = $_POST['datasets'];
		$basic = $_POST['basic'];
		$logical = $_POST['logical'];
		$unicode = $_POST['unicode'];
		$tool_defined = $_POST['tool_defined'];
		$special = $_POST['special'];
		$regex = $_POST['regex'];
		$date = getdate();

		// generate the list of test cases to run
		//$testcaselist = generate_test_case_list($hash_image, $hash_device, $bad_sector, $ops, $ops_rem, $ops_par, $hash, $err, $media, $partition, $interface);
		//natcasesort($testcaselist);

		if (file_exists($path."/".$filename)){ // test-configuration.txt already exists. archive 
			// the old one so we can write the new one.
			$filenamearchive = $filenamestem."-".$date["year"]."-".$date["mon"]."-".$date["mday"]."-".$date["hours"]."-".$date["minutes"]."-".$date["seconds"]."-bak.txt";
			//echo $path."/".$filename." already exists. Moving old ".$filename." to ".$filenamearchive."<br><br>";
			echo "<p><i>".$path."/".$filename."</i> already exists. Moving old <i>".$filename."</i> to <i>".$filenamearchive."</i></p>";

			if (rename($path."/".$filename, $path."/".$filenamearchive) != true){
				echo "<b><i>Error: </i></b>file copy ".$filename." to ".$filenamearchive." failed!";
			}
		}

		if (!$handle = fopen($path."/".$filename, 'w')){
			echo "<p><b>Error:</b> error encountered trying to open ".$path."/".$filename."</p>\n";
			$continue = 0;
		} else {
			//$db = new SQLite3('/tmp/ft-persistent-data.db');
			//$db->exec('CREATE TABLE pdata1 (path TEXT);
			//  CREATE TABLE tool (toolname TEXT, toolversion TEXT);
			//  CREATE TABLE hashes (hash TEXT);
			//  CREATE TABLE testcases (testcase TEXT);
			//');
			// load the path into our sqlite db
			//$db->exec("INSERT INTO pdata1 VALUES ('$path');");
			//INSERT INTO pdata1 VALUES ("/tmp");

			/* Write tool name, tool version and hash values to file (test report template 
			   configuration file) */
			fwrite($handle, "toolname ".$toolname."\n"); 
			fwrite($handle, "toolversion ".$toolversion."\n");	
			fwrite($handle, "se_other_name ".$se_other_name."\n"); 
			//$db->exec("INSERT INTO tool VALUES ('$toolname','$toolversion');");
			fwrite($handle, "engines ");	
			foreach ($engines as $value){ // connections may have several values
				fwrite($handle, $value." ");	
				//$db->exec("INSERT INTO hashes VALUES ('$value');");
			}
			fwrite($handle, "\n");	
			fwrite($handle, "datasets ");	
			foreach ($datasets as $value){ // connections may have several values
				fwrite($handle, $value." ");	
				//$db->exec("INSERT INTO hashes VALUES ('$value');");
			}
			fwrite($handle, "\n");
			
			// write out to file the list of test cases 
			foreach ($basic as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}

			foreach ($logical as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}

			foreach ($unicode as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}
			
			foreach ($tool_defined as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}
			
			foreach ($special as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}
			
			foreach ($regex as $testcase){
				fwrite($handle, $testcase."\n");	
				// fill our $testcases array
				$testcases[] = $testcase;
			}
			
			// write date to config file
			fwrite($handle, "date ".$date["weekday"].", ".$date["month"]." ".$date["mday"].", ".$date["year"]." at ".$date["hours"].":".$date["minutes"]."\n");
			fclose($handle);
			//echo "'".$filename."' written to '".$path."'\n";
			echo "<p>'<i>".$filename."</i>' written to '<i>".$path."'</i></p>\n";

			/*			$stmt = $db->prepare('SELECT path FROM pdata1');
			   $result = $stmt->execute();
			   while ($row = $result->fetchArray()){
			   echo $row['path'];
			   }
			   $results = $db->query('SELECT bar FROM foo');
			 */			
		}
		
		// create the directory structure on the log drive for storing our test results
		foreach ($engines as $engine){
			/* we'll need a directory on our log drive (FT-LOGS) to store all the log files for each search engine 
			 * we test, e.g., /media/FT-LOGS/Indexed */
			if ($engine == "Other"){ // if the user selected "Other", append the name they provided
				$basedir = $path."/".$engine."_".$se_other_name;	
			} else {
				$basedir = $path."/".$engine;	
			}

			// if the directory isn't already there, we'll need to create it 
//			if ($continue && !file_exists($basedir)){ // is it already there?
			if ($continue && !file_exists($basedir)){ // is it already there?
			  if (!mkdir($basedir)){ // create the directory for this test case
				// case: error
				 echo "<p><b>Error:</b> <i>".basename($_SERVER['PHP_SELF'])."</i> encountered an error trying to create 
			<i>".$basedir."</i></p>\n";
				$continue = 0; // error trying to create the test case directory so don't continue
			  }
			}

			// now add subdirectories for each dataset we'll be testing
			foreach ($datasets as $dataset){
				/* we'll need a directory on our log drive (FT-LOGS) to store all the log files for each data set 
				 * we test, e.g., /media/FT-LOGS/Indexed/Windows */
				$nesteddir = $basedir."/".$dataset;

				// if the directory isn't already there, we'll need to create it 
				if ($continue && !file_exists($nesteddir)){ // is it already there?
				  if (!mkdir($nesteddir)){ // create the directory for this test case
					// case: error
					 echo "<p><b>Error:</b> <i>".basename($_SERVER['PHP_SELF'])."</i> encountered an error trying to create <i>".$nesteddir."</i></p>\n";
					$continue = 0; // error trying to create the test case directory so don't continue
				  }
				}
			}
		}
	} else { // case 2) not savetestconfigfile.php
		// does 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();
				$datasets = array();
				$se_other_name = "";
				
				// 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);
					} else if(strpos($line, "datasets") !== false){ 
					    $line_exploded = explode(" ", trim($line));
					    $datasets = array_slice($line_exploded, 1);
					} else if (strpos($line, "se_other_name") !== false){
						$line_exploded = explode(" ", trim($line));
						$se_other_name = implode(" ", array_slice($line_exploded, 1));
					} else if(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=\"./customizetest.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;
		}

		// I'm not sure how or if we will use them yet, but pull back any values for selected_dataset and 
		// selected_engine that we might have in a ss-last.txt file
		if ($continue){
			$lastfile = "ss-last.txt";
			// depending on where we're coming from, 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!
					// initialize...
					$last_ds = "";
					$last_se = "";

					// 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 hwb-config.txt failed for some reason
					echo "<p><b>Error:</b> error opening ".$path."/".$lastfile.".</p>";				
					$continue = 0;
				}
			}
		}			
	}
}

// If we haven't run into any errors, print/display the gui/let the user select which data set
// they will test
if ($continue) { 
	echo "<p>You've selected to test ".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>) of your tool using ".count($datasets)." datasets (<i>".$datasets[0];
	if (count($datasets) == 2) { 
		echo " &amp; ".$datasets[1]; 
	}
	echo "</i>).";
	echo ' </p>';
	echo '<ul>';
	echo "<li>Select a data set from 'Untested or Partially Tested Data Sets' and click the ";
	echo "'Select data set' button to test your tool against that data set. You can re-test a data set by selecting it from ";
	echo "'Tested Data Sets.'</li>";
	echo "<li>After you have completed testing for each data set, click <a href=\"/generatefinalreport.php?ref=ss&path=$path\">";
	echo "here</a> to generate a test report for the tests you've run and document your testing.</li>";
	echo '</ul>';
	
	
	

	
	
	echo '<form method="POST" action="selectsearchengine.php"> ';
	
	// initialize...
	$datasets_tested = array();
	$datasets_pending = array();

	// measure which datasets have been tested and which are pending
	foreach ($datasets as $dataset){
		// initialize...
		$is_ds_tested = TRUE;
		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.'/'.$dataset;
			} else {
				$base = $path . '/' . $engine . '/' . $dataset;
			}	
			if (!is_se_tested($dataset, $engine, $base, $testcases)){
				// if any of the search engines needs more tests run, the data set as a whole needs 
				// more tests run
				$is_ds_tested = FALSE;
			}
		}		
		if ($is_ds_tested) { // build a list of which data sets have been tested...
			$datasets_tested[] = $dataset;
		} else { // and those which are pending
			$datasets_pending[] = $dataset;
		}
	}

	// if we're coming from ft_ss_save_results.php, we want to prompt the user so that they have context for why they landed here
	if (strpos($_SERVER['HTTP_REFERER'], "ft_ss_save_results.php") !== false){ 		
//		echo '<p style="font-size: 1.5em;"><img src="/images/explode-3.png" alt="" height="45" width="45" style="margin:-9px -4px;">&nbsp;';
		echo '<p style="font-size: 1.5em;"><img src="/images/info_black-128x128.png" alt="" height="29" width="29" style="margin:-2px -2px;">&nbsp;';
		if ( count($datasets_pending) > 0 ) { // case: we have more data sets to test
			//echo "<p><i>YOU JUST FINISHED RUNNING ALL THE TEST CASES FOR DATASET: ".$last_ds.", SEARCH ENGINE: ".$last_se."</i></p>";
			//echo '<p><img src="/images/info_black-128x128.png" alt="" height="24" width="24" style="margin:0px 0;">';
			echo "YOU JUST FINISHED RUNNING ALL THE TEST CASES FOR DATASET: <i>".strtoupper($last_ds)."</i></p>";
		} else { // case: no more data sets to test; time to generate a test report
			echo "YOU JUST FINISHED RUNNING ALL THE TESTS!</p>";
//			echo '<p style="font-size: 1.5em; margin: 0em 0em; padding: 0em 0em 0.5em 0em;"><img src="/images/explode-3.png" alt="" height="45" width="45" style="margin:-9px -4px;">&nbsp;';
//			echo '<p style="font-size: 1.5em;"><img src="/images/explode-3.png" alt="" height="45" width="45" style="margin:-9px -4px;">';
			echo '<p style="font-size: 1.5em;"><img src="/images/info_black-128x128.png" alt="" height="29" width="29" style="margin:-2px -2px;">';
			echo "&nbsp;CLICK <a href=\"/generatefinalreport.php?ref=ss&path=$path\">HERE</a> ";
			echo "TO GENERATE A TEST REPORT FOR THE TESTS YOU'VE RUN AND DOCUMENT YOUR TESTING.</p>";			
		}
	} else {
		echo '<br>';	
	}
	
	$first = TRUE;
	
//	echo '<h2 style="color:#008000 ">Pending or Incomplete Test Cases</h2>';
//	echo '<h2 style="color:#008000 ">Pending or Incomplete Data Sets</h2>';
	echo '<h2 style="color:#008000 ">Untested or Partially Tested Data Sets</h2>';
 	if ( count($datasets_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: 90%;\">\n";
		// print table headings
		echo '<tr><td colspan="2" style="width: 40%; text-align: left;"><b>Data Set</b></th><td style="text-align: left;"><b>Description</b></th></tr>';
		// print each table row
		foreach ($datasets_pending as $dataset) {
			echo '<tr><td style="width: 5%; text-align: center;"><input name="selected_dataset" value="'.$dataset.'" type="radio" required'; 
			// we want to autoselect a data set for the user, but we may use one of two metrics for making the choice 
			if ($last_ds && in_array($last_ds, $datasets_pending)){ // if there is a ds that was previously selected and we've yet to finish testing it...
				if ($dataset == $last_ds){
					echo ' checked="checked"';
				}
			} else {
				// no previously selected ds
				if ($first){
					echo ' checked="checked"';
					$first = FALSE;
				}
			}			
			echo '></td>'; // radio button			
			echo "<td>".$dataset."</td>"; // test case name
			echo "<td>".$datasets_dict[$dataset]."</td></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 data set \" type=\"submit\"><br><br>";
	
//	echo '<h2 style="color:#008000">Completed Test Cases</h2>';
//	echo '<h2 style="color:#008000 ">Completed Data Sets</h2>';
	echo '<h2 style="color:#008000 ">Tested Data Sets</h2>';
	
	if ( count($datasets_tested) > 0 ){			
	    // if there are some completed test cases, print them here in a table
	    echo "<table class=\"bordered_table2\" style=\"width: 90%;\">\n";
	    // print table headings
	    echo '<tr><td colspan="2" style="width: 40%; text-align: left;"><b>Data Set</b></th><td style="text-align: left;"><b>Description</b></th></tr>';
	    // print each table row
	    foreach ($datasets_tested as $dataset) {
			echo '<tr><td style="width: 5%; text-align: center;"><input name="selected_dataset" value="'.$dataset.'" type="radio" required></td>'; // radio button
			echo "<td>".$dataset."</td>"; // test case name
			echo "<td>".$datasets_dict[$dataset]."</td></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
	//echo '<input name="toolname" value="'.$toolname.'" type="hidden">';
	//echo '<input name="toolversion" value="'.$toolversion.'" type="hidden">';
?>	
		

</form>
</p>

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

