<?php
# CSE 190 M, Spring 2012
# This web service accepts query parameters 'name' and 'gender'
# and searches rank.txt for a line of data about that name/gender
# and outputs that line as plain text.
# If the person is not found in the file, produces an HTTP 410 error.
#
# Example line of data from the file (name, gender, then 12 decade ranks):
# Aaron m 147 193 187 199 250 237 230 178 52 34 34 41 55

$name = get_parameter("name");
$gender = get_parameter("gender");

# search the input file for the line about the given name/gender
$matching_line = "";
$lines = file("rank.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
	if (preg_match("/^$name $gender /", $line)) {
		$matching_line = $line;
		break;
	}
}

if ($matching_line) {
	header("Content-type: text/plain");
	print $matching_line;
} else {
	# this person/gender was not found; issue HTTP error 410
	header("HTTP/1.1 410 Gone");
	die("HTTP/1.1 410 Gone - There is no data for this name/gender.");
}

# Returns the value of the given query parameter.
# If the parameter has not been passed, issues an HTTP 400 error.
function get_parameter($name) {
	if (isset($_GET[$name])) {
		return $_GET[$name];
	} else {
		header("HTTP/1.1 400 Invalid Request");
		die("HTTP/1.1 400 Invalid Request - you forgot to pass a '$name' parameter.");
	}
}
?>