\n"); foreach ($lines as $line) { if ((!$prefix && !$substring) || ($prefix && strpos(strtolower($line), $prefix) === 0) || ($substring && strpos(strtolower($line), $substring) !== FALSE)) { print("
  • $line
  • \n"); } } print("\n"); } else { # normal list query; return all names as plain text, one per line require_method("GET"); header("Content-type: text/plain"); print implode("\n", $lines); } } # Output XML data about a baby name's ranking in each decade. # Ought to use DOMDocument, but oh well. function query_rank() { global $RANK_FILE; global $START_YEAR; global $YEAR_INCREMENT; require_method("GET"); require_params("name", "gender"); $name = get_name(); $gender = get_gender(); $line = get_file_line($RANK_FILE, $name, $gender); if (!$line) { header("HTTP/1.1 410 Gone"); die("HTTP ERROR 410: Baby name '$name'" . ($gender ? " with gender '{$gender}'" : "") . " does not have any associated ranking data."); } header("Content-type: application/xml"); print "\n"; $tokens = preg_split("/[ ]+/", $line); print "\n"; for ($i = 3; $i < count($tokens); $i++) { # if ($tokens[$i] > 0) { print " " . $tokens[$i] . "\n"; # } } print "\n"; } # output a plain-text line describing a name's origin/meaning function query_meaning() { global $MEANINGS_FILE; require_method("GET"); require_params("name"); $name = get_name(); $line = get_file_line($MEANINGS_FILE, $name); if (!$line) { $line = "Top scientists are still trying to figure out what the heck this name means. For now, it is a mystery!"; } $line = preg_replace("/^" . strtoupper($name) . " /", "", $line); header("Content-type: text/html"); print "
    \n"; print "

    \n"; print " The name " . strtoupper($name) . " means ...\n"; print "

    \n"; print "
    \n"; print "

    \n"; print " $line\n"; print "

    \n"; print "
    \n"; } function query_celebs() { global $SERVER; global $USERNAME; global $PASSWORD; global $DATABASE; require_params("name", "gender"); $name = get_name(); $gender = get_gender(); $db = new PDO("mysql:dbname={$DATABASE};host={$SERVER}", $USERNAME, $PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $name_str = $db->quote($name); $name_like_str = $db->quote("{$name} %"); $gender_str = $db->quote($gender); #$rows = $db->query("SELECT a.* # FROM actors a # JOIN roles r ON r.actor_id = a.id # JOIN movies m ON m.id = r.movie_id # WHERE a.name LIKE {$name_str} # LIMIT 100"); $rows = $db->query("SELECT a.* FROM actors a WHERE (a.first_name = {$name_str} OR a.first_name LIKE {$name_like_str}) AND a.gender = {$gender_str} ORDER BY a.film_count DESC LIMIT 10"); # ought to use json_encode, but this code predates that function header("Content-type: application/json"); print "{\n"; print " \"actors\": [\n"; if ($rows) { $i = 0; foreach ($rows as $row) { $first = toASCII(trim($row["first_name"])); $last = toASCII(trim($row["last_name"])); $film_count = (int) $row["film_count"]; # trim out suffixes like "(I)" from first names $first = preg_replace("/\(.*\)$/", "", $first); if ($i > 0) { print ",\n"; } print " {\n"; print " \"firstName\": \"{$first}\",\n"; print " \"lastName\": \"{$last}\",\n"; print " \"filmCount\": {$film_count}\n"; print " }"; $i++; } } print "\n ]\n"; print "}\n"; } # Removes all characters except letters/numbers from a string, returns it function filter_chars($str) { return preg_replace("/[^A-Za-z0-9_]*/", "", $str); } # Returns the first line from the given file that contains the given text, # or dies with a 404 if not found. function get_file_line($file_name, $name, $gender = "") { if (!file_exists($file_name)) { header("HTTP/1.1 500 Server Error"); die("HTTP ERROR 500: Unable to read input file: $file_name"); } $text = file_get_contents($file_name); $lines = preg_split("/[\r]?\n/", $text); foreach ($lines as $line) { if (($gender && preg_match("/^$name $gender /i", $line)) || (!$gender && preg_match("/^$name /i", $line))) { return trim($line); } } return NULL; } # Returns filtered value of name parameter after checking it for validity. function get_name() { $name = ""; if (isset($_GET["name"])) { $name = trim(filter_chars($_GET["name"])); } if (!$name) { header("HTTP/1.1 400 Invalid Request"); die("HTTP ERROR 400 - Invalid request. Missing or empty name."); } return $name; } # Returns filtered value of gender parameter after checking it for validity. function get_gender() { $gender = ""; if (isset($_GET["gender"])) { $gender = filter_chars(strtolower($_GET["gender"])); } if (!$gender || ($gender != "m" && $gender != "f")) { header("HTTP/1.1 400 Invalid Request"); die("HTTP ERROR 400 - Invalid request. Missing or invalid gender. Must be one of \"m\" or \"f\"."); } return $gender; } # Ensures that the current HTTP request uses the given method # (e.g. GET or POST), otherwise crashes with an HTTP 400 error. function require_method($method) { if (!isset($_SERVER["REQUEST_METHOD"]) || $_SERVER["REQUEST_METHOD"] != strtoupper($method)) { header("HTTP/1.1 405 Method Not Allowed"); die("HTTP ERROR 405: Method Not Allowed - This type of query accepts only $method requests."); } } # Ensures the presence of certain query parameters, which may be passed as # var-args. Dies with an HTTP 400 error if not found. function require_params($params) { # allow calling as a var-args function if (!is_array($params)) { $params = func_get_args(); } $missing = array(); foreach ($params as $param) { if (!isset($_GET[$param])) { $missing[] = $param; } } if (count($missing) > 0) { header("HTTP/1.1 400 Invalid Request"); die("HTTP ERROR 400 - Invalid request. Missing required parameter" . (count($missing) > 1 ? "s" : "") . ": " . implode(", ", $missing) . "\n"); } } function has_param($name) { return isset($_GET[$name]) && $_GET[$name] !== ""; } function param_is_truthy($name) { return isset($_GET[$name]) && ( $_GET[$name] === "true" || $_GET[$name] === "1" || $_GET[$name] === "on" || $_GET[$name] === "yes"); } function toASCII($str) { # return strtr( # utf8_decode($str), # utf8_decode("ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"), # "SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"); return strtr($str, "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ", "SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"); } ?>