<?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: James R. Lyle
*/

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));
			}						
		}
	} 
}

// ...any other form variables from selectsearchengine.php.
$case_id = $_POST['case_to_run'];

$page_title = "SS - Save Results";

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

//$page_h1 = "Saving Test Results to FT-LOGS Drive";
$page_h1 = "Saving Test Case ".$case_id." Results";
include "ft_ss_need_logs.php";
include_once('../include/ss-global.php');

$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;
}

if($continue){ // 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 the drive's not mounted, suppress/do not print the rest of this page.

	// 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... array to store our list of test cases
			$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, "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;
					}
				} elseif (strpos($line, "se_other_name") !== false){
					$line_exploded = explode(" ", trim($line));
					$se_other_name = implode(" ", array_slice($line_exploded, 1));
				} elseif(strpos($line, "engines") !== false){ 
					$line_exploded = explode(" ", trim($line));
					$engines = array_slice($line_exploded, 1);
				}
			}
		} 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;
	}	
}

// Try to pull back the values for selected_dataset and selected_engine that we have 
// stored in ss-last.txt 
if ($continue){
	$lastfile = "ss-last.txt";
	// initialize...
	$selected_dataset = "";
	$selected_engine = "";

	if (file_exists($path."/".$lastfile)){ // can we find ss-last.txt?
		// 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));
					$selected_dataset = implode(" ", array_slice($line_exploded, 1));
				} else if(strpos($line, "selected_engine") !== false){ 
					$line_exploded = explode(" ", trim($line));
					$selected_engine = 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;
		}
	} else { // if ss-last.txt doesn't exist by now, something went wrong
		echo "<p><b>Error:</b> something went wrong. Couldn't find ".$path."/".$lastfile.".</p>";				
		$continue = 0;		
	}
}

if($continue){ // 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 the drive's not mounted, suppress/do not print the rest of this page.
	$dribble = fopen('/FedTest/media/cftt/FT-LOGS/dribble-save-results.txt','w');
	
fprintf ($dribble,"Have tool %d, engine %d, data set %d\n",$need_tool,
	$need_se, $need_ds);

fprintf($dribble,"Tool %s\n",$toolname);
fprintf($dribble,"Tool Version %s\n",$toolversion);
fprintf($dribble,"Engine %s\n",$selected_engine);
fprintf($dribble,"Data Set %s\n",$selected_dataset);
fprintf ($dribble, "<br>Start of form items list<br>\n");

	if ($selected_engine == "Other"){
		$engine_folder = $selected_engine."_".$se_other_name;
		$engine_name = $selected_engine." - ".$se_other_name;
	} else {
		$engine_folder = $selected_engine;
		$engine_name = $selected_engine;
	}
	
	$base = $path .'/'. $engine_folder . '/' . $selected_dataset;
	if (!file_exists($path.'/'.$engine_folder)){
		//mkdir($path.$selected_engine, 0777, true);
		echo "<p><b>Error:</b> something went wrong... ".$path.'/'.$engine_folder." does not exist.</p>";
		$continue = 0;
	}
	if (!file_exists($base)){
		//mkdir($base, 0777, true);
		echo "<p><b>Error:</b> something went wrong... ".$base." does not exist.</p>";
		$continue = 0;
	}

	fprintf ($dribble,"Base %s dir1 %s Case %s\n",$base, $path.'/'.$engine_folder,$dase_id);
	$run_log = fopen($base.'/'.$case_id.'.txt','w');

	fprintf ($run_log,"case:%s\n",$case_id);
	fprintf ($run_log,"engine:%s\n",$engine_name);
	fprintf ($run_log,"dataset:%s\n",$selected_dataset);
	fprintf ($run_log,"tool:%s\n",$toolname);
	fprintf ($run_log,"version:%s\n",$toolversion);
	fprintf ($run_log,"tester:%s\n",$_POST['who']);
	fprintf ($run_log,"host:%s\n",$_POST['host']);
	fprintf ($run_log,"date:%s\n",date ('Y-m-d H:m:s'));
	if ($case_id != ''){
		$who_did_it = fopen($path.'/'.'ss_ur.txt','w');
		fprintf ($who_did_it,"%s\n%s\n",$_POST['who'],$_POST['host']);
	}

	echo "<p>'<i>".$case_id.".txt</i>' written to '<i>".$base."</i>'</p>";
	
	echo '<div style="padding: .5em 1em .25em 1em; background: #eeeeee url(/images/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x;">';
	
	$intro_old = <<<END
	<p>Test Case: %s for %s Version %s using search engine %s on %s data set.</p>
	<p>Tester is %s</P>
	<p>Host is %s</P>
END;

	$intro = <<<END
	<p>Test case: <i>%s</i><br>
	Testing with Data Set: <i>%s</i>, Search Engine: <i>%s</i><br>
	Name of the person running the test: <i>%s</i><br>
	Identifier for the computer running the string search tool: <i>%s</i><br></p>
END;
	
	printf ($intro, $case_id, $selected_dataset, $engine_name, $_POST['who'],
		$_POST['host']);

//	printf ("<p>Log directory: %s</p>\n",$base);
    $keys = array_keys($_POST);
    foreach ($keys as $dongxi){
        fprintf ($dribble,"<br>DongXI: %s ",$dongxi);
        fprintf ($dribble," Value: [%s] \n",$_POST[$dongxi]);
		}
	/*
    foreach ($keys as $dongxi){
        fprintf ($dribble,"<br>DongXI: %s ",$dongxi);
        fprintf ($dribble," Value: [%s] \n",$_POST[$dongxi]);

		if (is_array(($_POST[$dongxi]))){
			printf ('ARRAY: ');
		}
		else {
			printf ('NOT: ');
		}

        printf ("<br>DongXI: %s ",$dongxi);
        printf (" Value: [%s] \n",$_POST[$dongxi]);
	}

*/
	/*
	printf ("\n<BR>ACTIVE:\n");
	*/
	if (isset($_POST['n_active'])){
		$na = $_POST['n_active'];
	}
	else {
		$na = "0";
	}
	if (isset($_POST['n_deleted'])){
		$nd = $_POST['n_deleted'];
	}
	else {
		$nd = "0";
	}
	if (isset($_POST['n_unalloc'])){
		$nu = $_POST['n_unalloc'];
	}
	else {
		$nu = "0";
	}
/*
	if (!empty($_POST['ActiveFiles'])){
		$afx = $_POST['ActiveFiles'];
		printf ("<BR>Active Files\n");
		if (is_array($afx)){
			printf ("<BR>active Files is an ARRAY\n");
		} else {
			printf ("<BR>active Files NOT an ARRAY\n");
		}
	}
	else {
		printf ("<BR>No active Files\n");
	}
*/
		fprintf ($dribble,"LIST the active_hits:\n");
	if (!empty($_POST['ActiveFiles'])){
		$x_active = count($_POST['ActiveFiles']);
		foreach ($_POST['ActiveFiles'] as $af){
			fprintf ($run_log,"active_hit:%s\n",trim($af));
			fprintf ($dribble,"active_hit:%s\n",trim($af));
		/*
			printf ("<BR>AF: %s\n",$af);
		*/
		}
	}
	else {
		$x_active = 0;
	}
		fprintf ($dribble,"LIST the deleted_hits:\n");
	if (!empty($_POST['DeletedFiles'])){
		$x_deleted = count($_POST['DeletedFiles']);
		foreach ($_POST['DeletedFiles'] as $af){
			fprintf ($run_log,"deleted_hit:%s\n",trim($af));
			fprintf ($dribble,"deleted_hit:%s\n",trim($af));
		/*
			printf ("<BR>AF: %s\n",$af);
		*/
		}
	}
	else {
		$x_deleted = 0;
	}
		fprintf ($dribble,"LIST the unallocated_hits:\n");
	if (!empty($_POST['UnallocFiles'])){
		foreach ($_POST['UnallocFiles'] as $af){
			fprintf ($run_log,"unalloc_hit:%s\n",trim($af));
			fprintf ($dribble,"unalloc_hit:%s\n",trim($af));
			/*
			printf ("<BR>AF: %s\n",$af);
		*/
		}
		$x_unalloc = count($_POST['UnallocFiles']);
		/*
		printf ("<BR>%d strings found of %s strings in unallocated space",
			count($_POST['UnallocFiles']),$_POST[n_unalloc]);
			*/
	}
	else {
		$x_unalloc = 0;
	}
	/*
	*/
	$n_meta_ref = 0;
	fprintf ($dribble,"Check for Meta\n");
	if (!empty($_POST['Ref'])){
		foreach ($_POST['Ref'] as $af){
			fprintf ($run_log,"meta_ref:%s\n",trim($af));
			$n_meta_ref = $n_meta_ref + 1;
		}
		/*
		$x_meta = count($_POST['Meta']);
		printf ("<BR>%d strings found of %s strings in unallocated space",
			count($_POST['UnallocFiles']),$_POST[n_unalloc]);
			*/
	}
$n_meta_hits = 0;
	if (!empty($_POST['Meta'])){
		fprintf ($dribble,"Got Meta Data\n");
		foreach ($_POST['Meta'] as $af){
			fprintf ($run_log,"meta_hit:%s\n",trim($af));
			fprintf ($dribble,"meta_hit:%s\n",trim($af));
			$n_meta_hits = $n_meta_hits + 1;
		}
		$x_meta = count($_POST['Meta']);
		/*
		printf ("<BR>%d strings found of %s strings in unallocated space",
			count($_POST['UnallocFiles']),$_POST[n_unalloc]);
			*/
	}
	echo "<p>Summary Results:<br><i>";
	if ($na > 0){
		printf ("%d strings found of %s strings in active files",$x_active,$na);
	}
	if ($nd > 0){
		printf ("<BR>%d strings found of %s strings in deleted files",$x_deleted,$nd);
	}
	if ($nu > 0){
		printf ("<BR>%d strings found of %s strings in unallocated space",$x_unalloc,$nu);
	}
	if ($n_meta_ref != 0){
		printf ("<BR>%d string targets found of %s string targets in meta-data space",$n_meta_hits,$n_meta_ref);
	}
	
	fprintf ($run_log,"n_active_targets:%s\nn_active_hits:%d\n",$na,$x_active);
	fprintf ($run_log,"n_deleted_targets:%s\nn_deleted_hits:%d\n",$nd,$x_deleted);
	fprintf ($run_log,"n_unalloc_targets:%s\nn_unalloc_hits:%d\n",$nu,$x_unalloc);

	echo "</i></p><p>Comments:<br><i>";
	if (!empty($_POST['comments'])){
		printf ("%s\n",$_POST['comments']);
		fprintf ($run_log,"comments:\n%s",$_POST['comments']);
	} else { 
		printf ("No comments");
	}
	
	echo "</i></p></div><br>";
	
	/*
	printf ("<BR>=============================\n<BR>");
	print_r($_POST);
	printf ("<BR>=============================\n");
	*/
	
	// measure whether the test we just finished completes the testing of the selected data set
	$is_ds_tested = TRUE; 	// initialize...

	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
			$eng_base = $path.'/'.$engine."_".$se_other_name.'/'.$selected_dataset;
		} else {
			$eng_base = $path . '/' . $engine . '/' . $selected_dataset;
		}

		if (!is_se_tested($selected_dataset, $engine, $eng_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){ // case 0: the test we just finished completes the testing of this data set
		echo '<form method="POST" action="/stringsearch/selectdataset.php">';			
	} elseif (is_se_tested($selected_dataset, $selected_engine, $base, $testcases)){
		// case 1: the test we just finished completes the testing of the current search engine, but other
		// search engines still need to be tested for this data set
		echo '<form method="POST" action="/stringsearch/selectsearchengine.php">';	
	} else {  // case 2: there are more tests to run for this search engine
		echo '<form method="POST" action="/stringsearch/ft_ss_select_case.php">';
	}

	echo '&nbsp;&nbsp;<input value="Continue" type="submit">';
	// pass along some values we'll want to have access to on the next page
	echo '</form>';

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

