<?php
/**    Copyright © 2007 World Wide Web Consortium,
   (Massachusetts Institute of Technology, European Research
    Consortium for Informatics and Mathematics, Keio
    University). All Rights Reserved. 

    This work is distributed under the W3C Software License
    [1] in the hope that it will be useful, but WITHOUT ANY
    WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  
    [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
  
require_once("mthlib.phi");
require_once("tests.phi");

// Parameter that defines which test suite is being run
$ts=$_GET["ts"];

// if no test case id, we display the default welcome page
if (!$ts) {
  WriteHTMLTop("Mobile Test Harness");
  echo "<p>The Mobile Test Harness, developed by the 
  <a href='/2005/MWI/Tests'>Mobile Web Initiative Test Suites Working Group</a>
   allows to wrap existing browser-base test cases to add navigation and results
   recording in a mobile-friendly manner.</p>\n" ;
  echo "<ul><li><a href='harness?test=start&amp;ts=cssmp'>start CSS MP</a>; <a href='results?ts=cssmp'>results</a></li>\n" ;
  echo "<li><a href='harness?test=start&amp;ts=svg'>start SVG Tiny</a>; <a href='results?ts=svg'>results</a></li>\n" ;
  echo "<li><a href='harness?test=start&amp;ts=encoding'>start Encoding Declaration test suite</a></li>\n" ;
  echo "<li><a href='http://www.w3.org/2007/03/dom-tests/intro'>start DOM Level 1 test suite</a> (automated) - <a href='results?ts=dom1'>results</a></li>\n" ;
  echo "</ul>\n" ;
  WriteHTMLFoot('$Id: harness.php,v 1.4 2007-11-28 15:29:07 dom Exp $');
  exit();
}

$testsuite = new Testsuite('',$ts);
if (!$testsuite->uri) {
  WriteErrorpage("Unknown test suite","There is no test suite known as <code>$ts</code>",404);
}


// POST means the user has submitted a result
if ($ts && $REQUEST_METHOD=="POST" ) {
  // test case that triggered the submission
  if (array_key_exists("undertest",$_POST)) {
    $undertest = $_POST["undertest"]; 
    $testcaseundertest = new TestCase();
    $testcaseundertest->load($testsuite->uri,$undertest);
  } else {
    $testcaseundertest = $testsuite->getTestCaseByUri($_POST["undertesturi"]);
  }
  // actual result associated to the submission
  $result = $_POST["result"];
  switch($result) {
  case "Pass [1]":
    $res = 1;
    break;
  case "Fail [2]":
    $res = 2;
    break;
  case "Cannot tell [3]":
    $res = 3;
    break;
  default:
    $res = 0;
  }
  // We get the value of the HTTP User-Agent header
  $useragent = $_SERVER["HTTP_USER_AGENT"];
  $tr = new TestResult();
  // and we record the result in the database
  if (!$tr->create($testsuite->uri,$testcaseundertest->uri,$res,$useragent)) {
    ob_start();
    if (isset($_SERVER["Application"])) {
      $_SERVER["Application"]->printErrors();
    }
    $errors = ob_get_contents() ;
    ob_end_clean();

    WriteErrorpage("Operation failed","While trying to record your result submission on the test <code>".$testcaseundertest->uri."</code> of the test suite <code>".$testsuite->uri."</code>, the following errors prevented to properly register the result:".$errors,500);
  }

  // The DOM Test suite is particular, in so that it can be automated on the client side
  if ($testsuite->uri=="http://www.w3.org/2007/03/dom-tests/") {
    $nexttc = $testsuite->getNextTestCaseByUri($testcaseundertest->uri);
    if ($nexttc->uri) {
      header("Status: 302 Redirect");
      header("Location: ".$nexttc->uri);
    } else {
      WriteHTMLTop("Mobile Test Harness");
      echo "<p>This was the last test, thank you for your participation!</p>\n" ;
  echo "<p>You can see the <a href='results?ts=".$ts."'>collected results for this test suite</a>.</p>\n" ;
      WriteHTMLFoot('$Id: harness.php,v 1.4 2007-11-28 15:29:07 dom Exp $');
      exit();
    }
  }
}


// rank of the current test case in the current test suite
$index = $_GET["test"];

if (!$index || $index=="start") {
	// Start page offering the user to select which set of test cases he want to run
	WriteHTMLTop(htmlify($testsuite->title),true);
	echo "<p>Thank you for offering to contribute results for the "
	.htmlify($testsuite->title)
	." using your browser (identified as ".$_SERVER["HTTP_USER_AGENT"].").</p>";
	echo "<p>This test suite contains ".$testsuite->count()." test cases";
	$countuntested = $testsuite->count($_SERVER["HTTP_USER_AGENT"]);
	if ($countuntested==$testsuite->count()) {
		echo ", none of which have been checked with this browser";
	} else if ($countuntested==0) {
		echo ", all of which have already been checked at least once with this browser";
	} else {
		echo ", $countuntested of which have not yet been tested with this browser";
	}
	echo ". You can choose
	to go through:</p><ul>";
	echo "<li><a href='harness?test=1&amp;ts=$ts'>the full test suite</a>
	 (although you can stop at any time without causing troubles)</li>\n";
	if ($countuntested!=0 && $countuntested!=$testsuite->count()) {
	  echo "<li>the <a href='harness?test=1&amp;ts=$ts&amp;group=_untested'>$countuntested test cases</a>
	 that have had no submitted results for your browser</li>\n";
	}
	echo "<li><form action='harness'>
	<input type='hidden' name='ts' value='$ts' />
	<input type='hidden' name='group' value='_ind' />
	just <label>one test: <select name='test'>";
	 $testsuite->loadtestcases();
	foreach($testsuite->testcases as $tc) {
	 	echo "<option value='".$tc->rank."'>".htmlify($tc->title)."</option>\n";
	}
	echo "</select></label> <input type='submit' value='Run one test case' /></form></li>";
	echo "</ul>";
	echo "<p><strong>Note</strong>: the harness adds automatically in each test case the number
	of remaining test cases and a form to submit results; these additions are not part of the
	orginal test cases, and their influence on the results should be ignored as much as possible.
	In case of doubt, please hit the 'Cannot Tell' button.</p>";
	WriteHTMLFoot('$Id: harness.php,v 1.4 2007-11-28 15:29:07 dom Exp $');
	exit();
}


$group = $_GET["group"];
$uafilter = "";
if ($group=='_untested') {
	$uafilter = $_SERVER["HTTP_USER_AGENT"];
}

if ($index-1==$testsuite->count($uafilter)) { // i.e. we just ran the last test of the series
  WriteHTMLTop("Mobile Test Harness");
  if ($group!='_ind') {
    echo "<p>This was the last test, thank you for your participation!
     You can submit results for <a href='harness'>other test suites as well</a>.</p>\n" ;
  } else {
  	echo "<p>Thank you for your contribution! You can 
  	<a href='harness?ts=$ts&amp;test=start'>go and pick another test case</a> 
  	or choose <a href='harness'>another test suite entirely</a></p>\n" ;
  }
  echo "<p>You can see the <a href='results?ts=".$ts."'>collected results for this test suite</a>.</p>\n" ;
  WriteHTMLFoot('$Id: harness.php,v 1.4 2007-11-28 15:29:07 dom Exp $');
  exit();
}

// Make sure we can't get over the limits
if ($index-1 > $testsuite->count($uafilter) || $index<0) {
  WriteErrorpage("Unknown test","<p>There is no test with rank $index.</p><p><a href='harness?ts=$ts'>Go back to this test suite start page</a> or to the <a href='harness'>harness start page</a>.</p> ".$index,404);
}






// Otherwise, we process the given test case by loading it from the Web


$testcase = new TestCase();
if (!$testcase->load($testsuite->uri,$index,$uafilter)) {
  WriteErrorpage("Test load failed","An error occurred when loading the $index test in ".$testsuite->uri,500);
} 
$html=file_get_contents($testcase->uri);

if ($testcase->markup=="xhtml") {
  $tagCloser = "/";
}

// We set a base href to make sure the relative links work as expected
$basehref = "<base href='".$testcase->uri."' $tagCloser>";

// ...  we create the form that will be inserted 
// at the end of the html testcase
if ($group!='_untested') {
	$counter = "(test ".$index." of ".$testsuite->count().")";
} else {
	$counter = "(".($testsuite->count($uafilter) - 1)." untested cases remaining)";
}
$nexttc = $index + 1;
if ($group=='_ind') {
	// go directly to the thank you page without collecting 20000$
	$nexttc = $testsuite->count() + 1;
} else if ($group=='_untested') {
	$nexttc = 1;
}
$form = "<p>$counter</p>
<form name='eval' action='http://www.w3.org/2007/03/mth/harness?test=".($nexttc)."&amp;ts=".$ts."&amp;group=$group' method='post'>
<div>"
.($group!='_untested' ? 
   "<input type='hidden' name='undertest' value='".$index."' $tagCloser>"
   : "<input type='hidden' name='undertesturi' value='".$testcase->uri."' $tagCloser>"
   )
."<input type='submit' name='result' value='Pass [1]' accesskey='1' $tagCloser>
<input type='submit' name='result' value='Fail [2]' accesskey='2' $tagCloser>
<input type='submit' name='result' value='Cannot tell [3]' accesskey='3' $tagCloser>
</div></form>";

// ... and we insert both the base href and the form
// with a regular expression replacement
$output = preg_replace("/<head>/","<head>$basehref",$html);
$output = preg_replace("/<\/body>/","$form</body>",$output);

header("Cache-Control: max-age:0");
$forcedContentType=FALSE;
foreach($testcase->headers as $header) {
  header($header);
  if (preg_match('/^Content-Type:/',$header)) {
  	$forcedContentType=TRUE;
  }
}
if ($testcase->markup=="xhtml" && !$forcedContentType) {
	contentNegotiationHeaders();
}
// and outputting the resulting page
print $output;

?>
