info343/lectures/ajax-with-xml/files/animalgame.php

<?php
   require(dirname(__FILE__) . '/db.php');
   
   error_reporting(E_ALL);
   ini_set('display_errors', true);
   $db->hide_errors();
   
   if (!isset($_GET['nodeid']))
      httpdie(400, "Please supply a node id.");
   
   $nodeid = isset($_GET['nodeid']) ? $_GET['nodeid'] : 1;
   $test = isset($_GET['test']) ? $_GET['test'] : false;
   $src = isset($_GET['src']) ? $_GET['src'] : false;
   
   $node_query = "SELECT * FROM nodes WHERE nodeid = '{$nodeid}'";
   $node = $db->get_row($node_query);
   
   if (!$node)
      httpdie(404, "Node not found.");
   
   if ($test) {
      // if depth is 3, fast-forward to leaf node by following "yes" node until
      // an answer is reached
      for ($curid = $nodeid, $i = 0; $curid != 1 && $i <= 3; $i++) {
         $curid = $db->get_var("SELECT parentid FROM graph WHERE childid = '{$curid}'");
      }
      if ($i == 4) {
         // depth is 3
         while ($node->type == "question") {
            $node = $db->get_row("SELECT * FROM nodes WHERE nodeid = (SELECT childid FROM graph WHERE parentid = '{$node->nodeid}' AND type = 'yes')");
         }
      }
   }
   
   ob_start();
   
   header('HTTP/1.1 200 OK');
   $xmlprolog = '<' . '?xml version="1.0" encoding="UTF-8"?' . '>';
   
   if ($node->type == "question") {
      $children_query = "SELECT childid as nodeid, graph.type FROM graph INNER JOIN nodes ON (childid = nodeid) WHERE parentid = '{$nodeid}' ORDER BY type";
      
      list($yes, $no) = $db->get_results($children_query);
      echo $xmlprolog . '
<node id="' . htmlspecialchars($node->nodeid) . '">
   <question>' . htmlspecialchars(htmlspecialchars_decode($node->text), ENT_NOQUOTES) . '</question>
   <yes nodeid="' . htmlspecialchars($yes->nodeid) . '" />
   <no nodeid="' . htmlspecialchars($no->nodeid) . '" />
</node>';
   } else {
      echo $xmlprolog . '
<node id="' . htmlspecialchars($node->nodeid) . '">
   <answer>' . htmlspecialchars(htmlspecialchars_decode($node->text), ENT_NOQUOTES) . '</answer>
</node>';
   }
   
   if ($src) {
      $teststr = ($test ? "&amp;test=true" : '');
      $code = "<pre>" . htmlspecialchars(ob_get_contents()) . "</pre>";
      $code = preg_replace('/(yes|no) nodeid=&quot;(.*)&quot;/', '$1 nodeid="<a href="?nodeid=$2&amp;src=true' . $teststr . '">$2</a>"', $code);
      ob_end_clean();
      echo $code;
   } else {
      header("Content-Type: application/xml");
      ob_flush();
   }
   
   function httpdie($code, $msg) {
      switch ($code) {
         case 400:
            header('HTTP/1.1 400 Bad Request');
            break;
         case 404:
            header('HTTP/1.1 404 Not Found');
            break;
         default:
            header('HTTP/1.1 200 OK');
      }
      header('Content-type: text/plain');
      die($msg);
   }
?>