<?php
/*	program ADVENT.C					*/

/* Program translated from BDSC version of Adventure by		*/
/* Matt Cox, April 2003 (because no-one had before :-)		*/
/*                                                              */

/* This program is free to use and distribute as long as you    */
/* retain credits to anyone and everyone whose contributed      */
/* along the way..                                              */
/*   Willie Crowther, Don Woods, JR Jaeger, Jerry Pohl,         */
/*   Matt Cox                                                   */




// change these to match your MYSQL database setup
$hostname="localhost";  // MYSQL host
$username="";           // username for MYSQL
$password="";           // password for MYSQL
$dbName="mgscox";       // name of database in which table 'cave' is stored


/*	WARNING: "advent.c" allocates GLOBAL storage space by	*/
/*		including "advdef.h".				*/
/*		All other modules use "advdec.h"		*/


//#include	"stdio.h"	/* drv = 1.1st file 2.def 3.A	*/
//#include	"advent.h"	/* #define preprocessor equates	*/
//#include	"advword.h"	/* definition of "word" array	*/
//#include	"advcave.h"	/* definition of "cave" array	*/
//#include	"advtext.h"	/* definition of "text" arrays	*/
//#include	"advdef.h"

//#define	strchr	index
$index=0;

//extern	int	fclose();
//extern	int	fgetc();
//extern	FILE	*fopen();
//extern	int	fputc();
//extern	long	ftell();
//extern	int	printf();
//extern	int	setmem();
//extern	int	scanf();
//extern	int	sscanf();
//extern	char	*strcat();
//extern	char	*strchr();
//extern	unsigned	strlen();
//extern	int	tolower();

include("adventh.php3");
include("advwordh.php3");
include("advcaveh.php3");
include("advtexth.php3");
include("advdefh.php3");
include("databasec.php3");
include("turnc.php3");
include("englishc.php3");
include("itverbc.php3");
include("verbc.php3");

// seed with microseconds
function make_seed() {

	list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}

function main()
{

global $dbugflg,$limit,$saveflg,$fd1,$fd2,$fd3,$fd4,$rflag,$saveflg,$words;
global $initialisecave,$answer65;
global $place,$rflag,$holding;
global $debug,$nodebug,$dbugflg,$reset,$dodeath;

        echo '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<head>
 <title>Adventure PHP</title>
 <meta http-equiv="pragma" content="no-cache">
</head>
<body><font face=verdana>
        ';

        if ($reset) $initialisecave=1;
        if ($dodeath) death(); // won't return if not being resurrected

	opentxt();  // open file handles to text files
	initplay(); // restore state from database

        if ($debug) $dbugflg=1;
        elseif ($nodebug) $dbugflg=0;
	
        srand(make_seed());

	if (!$answer65) { 
	  list($answer65,$answer)=yes(65, 1, 0);
	  if ($answer65 && $answer)
		$limit = 1000;
  	  elseif ($answer65)
		$limit = 330;
	}
	if ($answer65) {
	  dumpscreen();
	  while(turn()){}
 	}

	fclose($fd1);
	fclose($fd2);
	fclose($fd3);
	fclose($fd4);
	updatedb();
	echo '
</font></body>
        ';
	
	return;			                /* exit = ok	*/
}						/* end main	*/

/* ************************************************************	*/

/*
	Initialize integer arrays with sscanf
*/
//function scanint(pi, str)
//{
//
//	while (*str) {
//		if  ((sscanf(str, "%d,", pi++)) < 1)
//			bug(41);	/* failed before EOS	*/
//		while (*str++ != ',')	/* advance str pointer	*/
//			;
//	}
//	return;
//}

function scanint($pi,$loc,$str)
{

  $nums=explode(",",$str);
  foreach($nums as $num)
    $pi[$loc++]=$num;
  return $pi;
}

/*
	Initialization of adventure play variables
*/
function initplay()
{

global $initialisecave;
global $turns,$loc,$oldloc,$oldloc2;
global $newloc,$cond,$place,$fixed,$visited,$prop;
global $tally,$tally2,$limit,$lmwarn,$wzdark,$closing;
global $closed,$holding,$detail,$knflow,$clock,$clock2;
global $panic,$dloc,$dflag,$dseen,$odloc,$daltloc,$dkill;
global $chloc,$chloc2,$bonus,$numdie,$object,$gaveup;
global $foobar,$saveflg,$dbugflg,$actmsg,$answer65,$answer81,$answer22,$answer49,$screen;
global $MAXLOC,$MAXOBJ,$MAXSCREEN,$dodeath;
global $caveid;

for ($i=1;$i<=$MAXSCREEN;$i++)$screen[$i]="<br>";

if ($initialisecave) {

    $turns = 1;

	/* initialize location status array */
//	setmem(cond, (sizeof(int))*MAXLOC, 0);
//	scanint(&cond[1], "5,1,5,5,1,1,5,17,1,1,");
//	scanint(&cond[13], "32,0,0,2,0,0,64,2,");
//	scanint(&cond[21], "2,2,0,6,0,2,");
//	scanint(&cond[31], "2,2,0,0,0,0,0,4,0,2,");
//	scanint(&cond[42], "128,128,128,128,136,136,136,128,128,");
//	scanint(&cond[51], "128,128,136,128,136,0,8,0,2,");
//	scanint(&cond[79], "2,128,128,136,0,0,8,136,128,0,2,2,");
//	scanint(&cond[95], "4,0,0,0,0,1,");
//	scanint(&cond[113], "4,0,1,1,");
//	scanint(&cond[122], "8,8,8,8,8,8,8,8,8,");
$cond=scanint($cond,1,"5,1,5,5,1,1,5,17,1,1");
$cond=scanint($cond,13, "32,0,0,2,0,0,64,2");
$cond=scanint($cond,21, "2,2,0,6,0,2");
$cond=scanint($cond,31, "2,2,0,0,0,0,0,4,0,2");
$cond=scanint($cond,42, "128,128,128,128,136,136,136,128,128");
$cond=scanint($cond,51, "128,128,136,128,136,0,8,0,2");
$cond=scanint($cond,79, "2,128,128,136,0,0,8,136,128,0,2,2");
$cond=scanint($cond,95, "4,0,0,0,0,1");
$cond=scanint($cond,113, "4,0,1,1");
$cond=scanint($cond,122, "8,8,8,8,8,8,8,8,8");

	/* initialize object locations */
//	setmem(place, (sizeof(int))*MAXOBJ, 0);
//	scanint(&place[1], "3,3,8,10,11,0,14,13,94,96,");
//	scanint(&place[11], "19,17,101,103,0,106,0,0,3,3,");
//	scanint(&place[23], "109,25,23,111,35,0,97,");
//	scanint(&place[31], "119,117,117,0,130,0,126,140,0,96,");
//	scanint(&place[50], "18,27,28,29,30,");
//	scanint(&place[56], "92,95,97,100,101,0,119,127,130,");
$place=scanint($place,1, "3,3,8,10,11,0,14,13,94,96");
$place=scanint($place,11, "19,17,101,103,0,106,0,0,3,3");
$place=scanint($place,23, "109,25,23,111,35,0,97");
$place=scanint($place,31, "119,117,117,0,130,0,126,140,0,96");
$place=scanint($place,50, "18,27,28,29,30");
$place=scanint($place,56, "92,95,97,100,101,0,119,127,130");

	/* initialize second (fixed) locations */
//	setmem(fixed, (sizeof(int))*MAXOBJ, 0);
//	scanint(&fixed[3], "9,0,0,0,15,0,-1,");
//	scanint(&fixed[11], "-1,27,-1,0,0,0,-1,");
//	scanint(&fixed[23], "-1,-1,67,-1,110,0,-1,-1,");
//	scanint(&fixed[31], "121,122,122,0,-1,-1,-1,-1,0,-1,");
//	scanint(&fixed[62], "121,-1,");
$fixed=scanint($fixed,3, "9,0,0,0,15,0,-1");
$fixed=scanint($fixed,11, "-1,27,-1,0,0,0,-1");
$fixed=scanint($fixed,23, "-1,-1,67,-1,110,0,-1,-1");
$fixed=scanint($fixed,31, "121,122,122,0,-1,-1,-1,-1,0,-1");
$fixed=scanint($fixed,62, "121,0");

	/* initialize default verb messages */
//	scanint(actmsg, "0,24,29,0,33,0,33,38,38,42,14,");
//	scanint(&actmsg[11], "43,110,29,110,73,75,29,13,59,59,");
//	scanint(&actmsg[21], "174,109,67,13,147,155,195,146,110,13,13,");
$actmsg=scanint($actmsg,0, "0,24,29,0,33,0,33,38,38,42,14");
$actmsg=scanint($actmsg,11, "43,110,29,110,73,75,29,13,59,59");
$actmsg=scanint($actmsg,21, "174,109,67,13,147,155,195,146,110,13,13");

//	/* initialize various flags and other variables */
//	setmem(visited, (sizeof(int))*MAXLOC, 0);
//	setmem(prop, (sizeof(int))*MAXOBJ, 0);
//	setmem(&prop[50], (sizeof(int))*(MAXOBJ-50), 0xff);
for ($i=0;$i<=$MAXLOC;$i++)$visited[$i]=0;
for ($i=0;$i<=50;$i++)$prop[$i]=0;
for ($i=50;$i<=$MAXOBJ;$i++) 
  if ($place[$i]) {
    $prop[$i]=-1; // -1 indicates its a treasure
    $tally+=1;    // track the number of treasures
  }
$prop[64] = 2; // chain

	$wzdark = $closed = $closing = $holding = $detail = 0;
	$limit = 100;
//	$tally = 15; calculated as per original fortran above
	$tally2 = 0;
	$newloc = 1;
	$loc = $oldloc = $oldloc2 = 1;
	$knfloc = 0;
	$chloc = 114;
	$chloc2 = 140;
/*	dloc[DWARFMAX-1] = chloc				*/
//	scanint(dloc, "0,19,27,33,44,64,114,");
//	scanint(odloc, "0,0,0,0,0,0,0,");
$dloc=scanint($dloc,0,"0,19,27,33,44,64,114");
$odloc=scanint($odloc,0,"0,0,0,0,0,0,0");
	$dkill = 0;
//	scanint(dseen, "0,0,0,0,0,0,0,");
$dseen=scanint($dseen,0,"0,0,0,0,0,0,0");
	$clock = 30;
	$clock2 = 50;
	$panic = 0;
	$bonus = 0;
	$numdie = 0;
	$daltloc = 18;
	$lmwarn = 0;
	$foobar = 0;
	$dflag = 0;
	$gaveup = 0;
	$saveflg = 0;
	$knflow=0;
	$answer65=$answer81=$answer22=$answer49=0;
	
    updatedb();
 }
  
else {
  $query="SELECT entry,screen FROM cave WHERE id=$caveid";
  $result=MYSQL_QUERY($query); print MYSQL_ERROR();
  $entry=stripslashes(MYSQL_RESULT($result,0,'entry')); 

  list($turns,$loc,$oldloc,$oldloc2,
       $newloc,$arrcond,$arrplace,$arrfixed,$arrvisited,$arrprop,
       $tally,$tally2,$limit,$lmwarn,$wzdark,$closing,
       $closed,$holding,$detail,$knflow,$clock,$clock2,
       $panic,$arrdloc,$dflag,$arrdseen,$arrodloc,$daltloc,$dkill,
       $chloc,$chloc2,$bonus,$numdie,$object,$gaveup,
       $foobar,$saveflg,$dbugflg,$arractmsg,$answer65,$dodeath,$answer22,$answer49,
       $keyscond,$keysplace,$keysfixed,$keysvisited,$keysprop,$keysdloc,$keysodloc,$keysdseen,$keysactmsg) =
    explode(",",$entry);
    
  $acond=explode("/",$arrcond);
  $aplace=explode("/",$arrplace);
  $afixed=explode("/",$arrfixed);
  $avisited=explode("/",$arrvisited);
  $aprop=explode("/",$arrprop);
  $adloc=explode("/",$arrdloc);
  $aodloc=explode("/",$arrodloc);
  $adseen=explode("/",$arrdseen);
  $aactmsg=explode("/",$arractmsg);

  $akeyscond=explode("/",$keyscond);
  $akeysplace=explode("/",$keysplace);
  $akeysfixed=explode("/",$keysfixed);
  $akeysvisited=explode("/",$keysvisited);
  $akeysprop=explode("/",$keysprop);
  $akeysdloc=explode("/",$keysdloc);
  $akeysodloc=explode("/",$keysodloc);
  $akeysdseen=explode("/",$keysdseen);
  $akeysactmsg=explode("/",$keysactmsg);
  
  $index=0;
  foreach($akeyscond as $key)
    $cond[$key]=$acond[$index++];
  $index=0;
  foreach($akeysplace as $key)
    $place[$key]=$aplace[$index++];
  $index=0;
  foreach($akeysfixed as $key)
    $fixed[$key]=$afixed[$index++];
  $index=0;
  foreach($akeysvisited as $key)
    $visited[$key]=$avisited[$index++];
  $index=0;
  foreach($akeysprop as $key)
    $prop[$key]=$aprop[$index++];
  $index=0;
  foreach($akeysdloc as $key)
    $dloc[$key]=$adloc[$index++];
  $index=0;
  foreach($akeysodloc as $key)
    $odloc[$key]=$aodloc[$index++];
  $index=0;
  foreach($akeysdseen as $key)
    $dseen[$key]=$adseen[$index++];
  $index=0;
  foreach($akeysactmsg as $key)
    $actmsg[$key]=$aactmsg[$index++];
    
  $arrscreen=stripslashes(MYSQL_RESULT($result,0,'screen')); 
  str_replace("~",",",$arrscreen);
  $screen=explode("¬",$arrscreen);
  
 }
}

function updatedb() {

global $turns,$loc,$oldloc,$oldloc2;
global $newloc,$cond,$place,$fixed,$visited,$prop;
global $tally,$tally2,$limit,$lmwarn,$wzdark,$closing;
global $closed,$holding,$detail,$knflow,$clock,$clock2;
global $panic,$dloc,$dflag,$dseen,$odloc,$daltloc,$dkill;
global $chloc,$chloc2,$bonus,$numdie,$object,$gaveup;
global $foobar,$saveflg,$dbugflg,$actmsg,$answer65,$dodeath,$answer22,$answer49,$screen;
global $caveid;


   $arrcond=implode("/",$cond);
   $arrplace=implode("/",$place);
   $arrfixed=implode("/",$fixed);
   $arrvisited=implode("/",$visited);
   $arrprop=implode("/",$prop);
   $arrdloc=implode("/",$dloc);
   $arrodloc=implode("/",$odloc);
   $arrdseen=implode("/",$dseen);
   $arractmsg=implode("/",$actmsg);
   
   $akeyscond=array_keys($cond);
   $akeysplace=array_keys($place);
   $akeysfixed=array_keys($fixed);
   $akeysvisited=array_keys($visited);
   $akeysprop=array_keys($prop);
   $akeysdloc=array_keys($dloc);
   $akeysodloc=array_keys($odloc);
   $akeysdseen=array_keys($dseen);
   $akeysactmsg=array_keys($actmsg);
   
   $keyscond=implode("/",$akeyscond);
   $keysplace=implode("/",$akeysplace);
   $keysfixed=implode("/",$akeysfixed);
   $keysvisited=implode("/",$akeysvisited);
   $keysprop=implode("/",$akeysprop);
   $keysdloc=implode("/",$akeysdloc);
   $keysodloc=implode("/",$akeysodloc);
   $keysdseen=implode("/",$akeysdseen);
   $keysactmsg=implode("/",$akeysactmsg);
   

   $entry="$turns,$loc,$oldloc,$oldloc2,".
       "$newloc,$arrcond,$arrplace,$arrfixed,$arrvisited,$arrprop,".
       "$tally,$tally2,$limit,$lmwarn,$wzdark,$closing,".
       "$closed,$holding,$detail,$knflow,$clock,$clock2,".
       "$panic,$arrdloc,$dflag,$arrdseen,$arrodloc,$daltloc,$dkill,".
       "$chloc,$chloc2,$bonus,$numdie,$object,$gaveup,".
       "$foobar,$saveflg,$dbugflg,$arractmsg,$answer65,$dodeath,$answer22,$answer49,".
       "$keyscond,$keysplace,$keysfixed,$keysvisited,$keysprop,$keysdloc,$keysodloc,$keysdseen,$keysactmsg";
   $entry=addslashes($entry);    
   $query="UPDATE cave SET entry='$entry' WHERE id=$caveid";
   $result=MYSQL_QUERY($query); print mysql_error();
}

/*
	Open advent?.txt files
*/
function opentxt()
{
global $fd1,$fd2,$fd3,$fd4;
	$fd1 = fopen("advent1.txt", "r");
	if (!$fd1) {
		print("Sorry, I can't open advent1.txt...<br>");
		exit();
	}
	$fd2 = fopen("advent2.txt", "r");
	if (!$fd2) {
		printf("Sorry, I can't open advent2.txt...<br>");
		exit();
	}
	$fd3 = fopen("advent3.txt", "r");
	if (!$fd3) {
		printf("Sorry, I can't open advent3.txt...<br>");
		exit();
	}
	$fd4 = fopen("advent4.txt", "r");
	if (!$fd4) {
		printf("Sorry, I can't open advent4.txt...<br>");
		exit();
	}
}


/* ************************ Main Routine *********************** */


// Connect to database
$mysqlHandle = mysql_pconnect( $hostname, $username, $password );
if( $mysqlHandle == false ) die("mysqlhandle:Wrong Host/ Username/ Password combination");

// Select database
if (!mysql_select_db( "$dbName"))
 mysql_create_db("$dbName") or dodie("Unable to create to database $dbName");

// Create table cave is requested
if ($install) {
  print "Searching for existing installation. List of installed tables...<br>";
  $result=mysql_list_tables("$dbName");
  $foundit==0;
  for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $tname=mysql_tablename($result, $i);
    print "Table ".($i+1).": '$tname'<br>";
    if (!strcmp($tname,"cave")) $foundit=1; //strcmp returns 0 on match
  }
  if ($foundit) {
    print "Table 'cave' found. Removing it..<br>";
    $query="DROP TABLE cave";
    $result=mysql_query($query); print mysql_error()."\n";
    if (mysql_errno()) die("MySQL error occured - check drop table permissions.");
  }
  print "Creating table 'cave'..<br>";
  $query="CREATE TABLE cave (entry longtext, id int(11) not null, screen longtext, primary key (id))";
  $result=mysql_query($query); print mysql_error()."\n";
  if (mysql_errno()) die("MySQL error occured - check create table permissions.");
  
  // check we can write to it
  $query="INSERT INTO cave VALUES ('',1,'')";
  $result=mysql_query($query); print mysql_error()."\n";
  if (mysql_errno()) die("MySQL error occured - check update table permissions.");
 
  die("Table 'cave' created. You can now play Adventure (aka Collosal Cave).");
}

$caveid = $HTTP_COOKIE_VARS["caveid"];

if ($forgetme) {
  $hash=$caveid;
  setcookie("caveid","");
  $query="DELETE FROM cave WHERE id=$hash";
  $result=MYSQL_QUERY($query); print "$query:".mysql_error()."\n";
  $caveid=0;
}

if (!$caveid && !$formcaveusername) 
  echo '
<h1>Welcome to Adventure</h1>
<p>In order to play adventure you need to enter a unique username to distinguish
your saved games from everybody else. Please enter your choice below.</p>
<form method=post action=?unsubmit=1><input name=formcaveusername><input type=submit name=Go!>
</form>
  ';

elseif ($formcaveusername) {
  $hash=crc32($formcaveusername);
  $query="SELECT * FROM cave WHERE id = $hash";
  $result=MYSQL_QUERY($query); //print mysql_error()."\n";
  if (MYSQL_NUMROWS($result))
    echo '
<h1>Username already taken</h1>
<p>Please enter an alternative username to distinguish
your saved games from everybody else. Please enter your choice below.</p>
<form method=post action=?unsubmit=1><input name=formcaveusername><input type=submit name=Go!>
</form>
    ';
  else {
    $caveid=$hash;
    setcookie("caveid","$caveid");
    $query="INSERT INTO cave VALUES ('',$caveid,'')";
    $result=mysql_query($query); print mysql_error()."\n";
    $reset=1;
  }
}

if ($caveid) main();

?>
