<?php
/* XML Chat Server.
   This script returns an XML document! 
   If there are any errors, the document returned includes the tag
     <status> with the value "Error", otherwise "Success". An error
     document looks like this:
<chat>
  <status>Error</status>
  <message>some error message</message>
</chat>


If everything works, the document returned includes a list 
of chat messages. Each message has an id (a number) and 
the actual text. There is no notion of a user (there is nothing
that says who sent what message). A document that includes a
list of messages looks like this:

<chat>
  <status>Success</status>
  <messages>
    <message id="1">Hello</message>
    <message id="2">sldkfj</message>
    <message id="3">sd;lfk;sldfk</message>
    <message id="4">dlskjf</message>
    <message id="5">sldkjf</message>
    <message id="6">joe</message>
  </messages>
</chat>

Form Fields Processed:

msg:  This script looks for a form field named "msg". If one is found,
      the value of this form field is posted as a new message in the
      message database.

first: The script will return all messages with message id greater than
      or equal to the value of this field. 
      A browser could always send the value of first as one more than 
      the largest ID it currently has.
*/

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header('Content-Type: text/xml');

$username="php"; /* Your MySQL username/password goes here! */
$password="php";
$database="chat";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

// if msg was sent - add it to the database
if ($_REQUEST['msg']) {
  $msg = mysql_real_escape_string($_REQUEST['msg']);
  $ip = $_SERVER['REMOTE_ADDR'];
  $msg = "$ip: $msg";
  $res=mysql_query("INSERT INTO messages SET msgtxt='$msg'");
  if (! $res) {
	error_response("Insert Failed " . mysql_error());
	exit;
  }
}

// build a query to extract all messages greater than first
if ($_REQUEST['first']) {
  $query = "SELECT * FROM messages WHERE msgid >= " . 
        $_REQUEST['first'] . " ORDER BY msgid";
} else {
  // no first - grab them all
  $query = "SELECT * FROM messages ORDER BY msgid";
}

// submit the query to the database
$res=mysql_query($query);

// make sure it worked!
if (!$res) {
  error_response(mysql_error());
  exit;
}

$num = mysql_numrows($res);
echo "<chat>
  <status>Success</status>
  <messages>\n";
for ($i=0;$i<$num;$i++) {
  $mid = mysql_result($res,$i,'msgid');
  $mtxt = mysql_result($res,$i,'msgtxt');
  echo "    <message msgid='$mid'>$mtxt</message>\n";
}
echo "  </messages>
</chat>\n";

function error_response($s) {
echo "<chat>
  <status>Error</status>
  <message>$s</message>
</chat>\n";
}
?>