#!/usr/bin/perl

$author_name = "Dan Parslow";
$author_mail = "dan\@parslow.com";
$method = $ENV{'REQUEST_METHOD'};
$script = $ENV{'SCRIPT_NAME'};
$query = $ENV{'QUERY_STRING'};
$referer = $ENV{'HTTP_REFERER'};
$stateLocked = "L";
$stateInvisible = "I";
$stateActive = "A";
$stateArchived = "R";

$quick = 0;
$extend = 0;
$base_extend = 40;
$quick_default = 8;

# security stuff
@badsource = ( "eye-of-newt" );

if ( ! &checkReferer()) {
    &dispBlank();
    exit( 0);
}

$stdauth = "8a1c6d1d";
# @shitlist = (  "24.241", "62.64", "212.188", "212.250" );

# if ( ! &checkSecurity()) {
#    &dispBlank();
#    exit( 0);
# }
# end of security stuff

&setPairs( $query);

$game_sizedefault = "quick";
if (( $quick > 0) && ( $quick != $quick_default))
{
    $game_sizedefault = $game_sizedefault . "=" . $quick;
}


$document_root = ".";
$game_root = "/usr/local/mornington";
$image_dir = $document_root . "/images/";
$game_dir = $game_root . "/games/";
$exclusive_lock = 2;
$unlock = 8;

$colourDefault = "default";
$colourSel{ "default" } = "checked";
$colourSel{ "blue" } = "";
$colourSel{ "green"} = "";
$colourSel{ "red" } = "";
$colourSel{ "3913668"} = "";
$colourSel{ "$D8E00" } = "";
$colourSel{ "saddlebrown" } = "";

$game_literal = "Game_";
$game_ext = ".txt";
$game_num = $query;
$full_path = $game_dir . "ActiveGames" . $game_ext;
$game_path = $game_dir . $game_literal . $game_req . $game_ext;
$next_path = $game_dir . "NextGame" . $game_ext;
$game_title = "";
$game_intro = "";
$game_state = "A";
$moved = 0;
$game_won = 0;
$main_script = "./pda.pl";
$name_preload = "";
$move_preload = "";
$std_winning_move = "mornington crescent";
$move_prompt = "";
$lt="%3C";
$gt="%3E";

$home_ref = $main_script;

if (( $quick != $quick_default) && ( $quick > 0))
{
    $home_ref = $home_ref . "\?quick=$quick";
}

$body_color = "F3F3F3";
#$move_color = "white";
#$list_open = "<CENTER><TABLE width='90%' cellpadding=4>";
#$list_close = "</table></center>";
#$list_open_elem = "<TR bgcolor=$move_color><TD>\n";
#$list_close_elem = "</td></tr>";

#some HTML body values

$body_bgcolor = "#ECECEC";
$body_background = "bg_stc.gif";
$body_text = "#000000";
$body_link = "#0000FF";
$body_alink="#FF2020";
$body_vlink = "#800020";

$list_open="<UL>";
$list_close="</ul>";
$list_open_elem="<LI>";
$list_close_elem="";

$narrative_open="<I>";
$narrative_close="</i>";



if ( $method eq "POST") {
# user pressed submit on the move page
# first, parse out the form.

	&parse_form_data( *FORM);
	$user_name = $FORM{'name'};
	$user_move = $FORM{'move'};
	$game_intro = $FORM{'game_intro'};

	
# if this was a game create action, try to do it.
	if ( $FORM{'move_type'} eq "create") {
		if ( ! &newGame()) {
			&gameFailed();
			exit(0);
		}
		$game_action = "move";
	} else {
		if ( ! &getGame() ) {
			&invalidGame();
			exit(0);
		}
	}

# we are now in a "move" state

# game should exist at this point, one way or another.
# post the move.
	
	
	$source = $ENV{'REMOTE_ADDR'};
	$dayTime = &getDayTime();	

    ($tmp1 = $user_name) =~ s/\s//eg;
	$tmp1 =~ s/$lt(.*?)$gt//g;
    ($tmp2 = $user_move) =~ s/\s//eg;
    ($tmp3 = $game_intro) =~ s/\s//eg;

# player must enter a name and either an intro or a move
	if (( $tmp1 ne "") &&
		(( $tmp2 ne "") || ( $tmp3 ne ""))) {

		$cvt_move = $user_move;
		$cvt_move =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
		$cvt_move =~ s/\<\/IFRAME/PLEASE_DONT_POST_THIS/i;
		$cvt_name = $user_name;
		$cvt_name =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
		if ( $FORM{'magic_number'} < $total_move_count) {
			$game_title = "Simulpost - move not entered";
			$move_prompt = "Another user entered a move before yours.  Would you like to reenter your move?<br>";
			$name_preload = $cvt_name;
			$move_preload = $cvt_move;
			$colourSel{ $colourDefault } = "";
			$colourSel{ $FORM{ "colour" }} = "checked";
			
		    } elsif ( &badHTML( $cvt_move)) {
            $game_title = "HTML Error - move not entered";		    
	    $move_prompt = "Your move appeared to contain an HTML error.  Do you want to edit it and try again?<br>";
	    $move_preload = $cvt_move;
	    $name_preload = $cvt_name;
	    $colourSel{ $colourDefault } = "";
	    $colourSel{ $FORM{ "colour" }} = "checked";

	} else {

			open ( GAMEFILE, ">>" . $game_path)
				|| die "Could not open requested game file $game_path\n";
			flock ( GAMEFILE, $exclusive_lock);

			if ( $game_intro ne "") {
				print GAMEFILE "$dayTime\~$source\~MC-NARRATIVE\~$game_intro\n";
				$total_move_count++;
			}

			if ( $user_move ne "") {
			    $useColour = ( $FORM{"colour"} ne $colourDefault ? $FORM{ "colour" } : "");
				print GAMEFILE "$dayTime\~$source\~$user_name\~$user_move\~$useColour\n";
				$total_move_count++;
			}

			$game_title = "Your move has been added";

			if ( $game_won = &checkGameWon()) {
				print GAMEFILE "$dayTime\~MC-REMARK\~MC-REMARK\~Game won by $user_name.\n";
				$total_move_count++;
				$game_title = "You have won game $game_label!";
				$name_preload = "$user_name (Winner's Comments)";
				$name_preload =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
				$move_prompt = "Congratulations!\n<br>Any deathless remarks for the admiring masses?\n<br>Or would you prefer to <A href='$main_script'>return to the main page</a>?<br>";
			
			}
			
			flock ( GAMEFILE, $unlock);
			close ( GAMEFILE);

			&updateActiveGames( $game_won, $user_name, $dayTime);
		
			$moved = 1;
		}
	}

	&printHeader();
	
	&displayGame();

    if ( $game_state ne $stateLocked)
    {
	print STDOUT <<End_Of_Start_Form;

<FORM method="POST" action="$script?$game_number\&$game_sizedefault">
	<INPUT type="hidden" name="move_type" value="move">
End_Of_Start_Form
    }

} else {
# user clicked in on a game play or create link

    $exists = &getGame();

	
# check for initial creation attempt.

	if ( $game_action eq "create") {

		if ( $exists) {
			&gameFailed();
			exit( 0);
		}
		
		$game_title = "Creating Game $game_req";

		&printHeader();

		print STDOUT <<End_Of_Create_Form;

<FORM method="POST" action="$script?$game_req\&$game_sizedefault">
<PRE>
<EM>Game Name</em>:
        <INPUT type="text" name="game_name" size=32>
</pre>
Note: in order for the server to create a game, you must enter a name for it,
and either an opening move or an introduction, or both.  It is also essential
to put in your own name, as the server never accepts anonymous submissions.
<P>

An Introduction is an optional place to enter any special rules or 
other opening remarks. If you include one it will automatically appear 
in italics (no markup necessary) at the start of the game.  Note that 
this is a good place to mention the goal of the game, as it will 
not end the game if used here.

<P>
<PRE>
<EM>Introduction</em>:
        <TEXTAREA name="game_intro" rows=3 cols=32 wrap="physical"></textarea>
</pre>
	<INPUT type="hidden" name="game_number" value="$game_req">
	<INPUT type="hidden" name="move_type" value="create">
End_Of_Create_Form

	} else {

# this is nowt but a standard game play link
		
	    if ( ! $exists) {
		&invalidGame();
		exit(0);
	    }
		&printHeader();

		&displayGame();

        if ( $game_state ne "L")
        {
		    print STDOUT <<End_Of_MoveOnly_Form;

<FORM method="POST" action="$script?$game_number\&$game_sizedefault">
<INPUT type="hidden" name="move_type" value="move">
End_Of_MoveOnly_Form
        }

	}
}
# it's all the same after this


# now display the form's remainder

    if ( $game_state ne "L")
    {
	    print STDOUT <<End_Of_Content_Footer;
<INPUT type="hidden" name="magic_number" value="$total_move_count">
<TABLE border=0 cellpadding=0 cellspacing=0>
  <TR>
    <TD valign="top">
      <TABLE border=0>
        <TR>
          <TD valign="top">
            <EM>Name</em>:
          </td>
          <TD valign="top" colspan=2>
            <INPUT type="text" name="name" value="$name_preload" size=32>
          </td>
        </tr>
        <TR>
          <TD valign="top">
            <EM>Move</em>:
          </td>
          <TD valign="top">
            <TEXTAREA name="move" rows=3 cols=32 wrap="physical">$move_preload</textarea>
          </td>
        </tr>
        <TR>
          <TD>
          </td>
          <TD>
            <INPUT type="submit" value="Send">
            <INPUT type="reset" value="Clear">
          </td>
        </tr>
      </table>
    </td>
    <TD valign="bottom">
    <!-- British spelling just for a change -->
    <INPUT type="radio" name="colour" value="default" $colourSel{ $colourDefault} > <B>Black</b> <br>
    <INPUT type="radio" name="colour" value="blue" $colourSel{ "blue"}> <FONT color="blue"><B>Blue</b></font> <br>
    <INPUT type="radio" name="colour" value="green"  $colourSel{ "green"}> <FONT color="green"><B>Green</b></font> <br>
    <INPUT type="radio" name="colour" value="red" $colourSel{ "red"}> <FONT color="red"><B>Red</b></font> <br>
    <INPUT type="radio" name="colour" value="#913668" $colourSel{ "#913668"}> <FONT color="#913668"><B>Puce</b></font> <br>
    <INPUT type="radio" name="colour" value="#D8E000" $colourSel{ "#D8E000"}> <FONT color="#D8E000"><B>Chartreuse</b></font> <br>
    <INPUT type="radio" name="colour" value="saddlebrown" $colourSel{ "saddlebrown"}> <FONT color="saddlebrown"><B>Hampster</b></font>
    </td>
  </tr>
</table>
<P>
</form>
</body>
</html>
End_Of_Content_Footer

    } else {

        print STDOUT "<B>This game is now closed.</b>";
    }


# done.

exit( 0);


sub printHeader {

	if ( $game_title eq "") {
		$game_title = $game_name;
	}

        $game_label = $game_number;


	print <<End_Of_Content_Header;
Content-type: text/html
Pragma: no-cache
Cache-control: max-age=30, no-cache, must-revalidate

<HTML>
<HEAD>

<meta name="palmcomputingplatform" content="true">
<meta name="historylisttext" content="Game $game_number">

<META name="Keywords"
  content="Mornington Crescent, Mornington, ISIHAC, Cress, Cheddar Gorge, Limericks">
<META name="Generator" 
  content="Ultimate Crescent Server II: $script (Perl5)">

<TITLE>
Game $game_label
</title>
</head>

<BODY> 

End_Of_Content_Header

	if ( $game_action eq "create") {
		print STDOUT "<H2>Creating New Game $game_req</h2>" ,
			"\nEnter the game name, and optionally, an introduction and/or a move.\n" ,
					"<P>Note that the game must be named to be created.\n" ,
					"If the game requires a winning phrase other than <b>Mornington Crescent</b>, ",
					"you can set it by appending it to the game name, separated by a tilde (~), e.g. ",
					"<B><U>Elementary, My Dear Watson~baker street</u></b>. The win-detector is not case-sensitive."
	} else {
			print STDOUT	"\n<H2>\"$game_name\"</h2>" ,
						"<P>\n<HR>\n<P>";
	}

}

sub displayGame {

	open ( GAMEFILE, "<" . $full_path)
		|| die "Could not open requested game index file $full_path\n";
	flock ( GAMEFILE, $exclusive_lock);

	$game_count = 0;
	$active_count = 0;
	$revived = 0;
	$prev_num = "";
	$prev_name = "";
    $next_num = "";
    $next_name = "";
    $anum = "";
	$state_compare = ( $game_state =~ /L|R/ ? "L|R" : "A");
    $this_reached = 0;

	while ( $user_line = <GAMEFILE>) {
		$user_line =~ s/[\n\r]//eg;
		if ( $user_line) {
			$game_count++;
			$user_line =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
			($anum, $game_name, $astate) =
				split( /~/, $user_line);
			if (( $this_reached == 1) && ( $astate =~ /$state_compare/) && ( $next_num eq "")) {
			    $next_name = $game_name;
                $next_num = $anum;
			}
			if ( $anum eq $game_req) {
			    $game_number = $anum;
				$this_reached = 1;
			}
			if (( $this_reached == 0) && ( $astate =~ /$state_compare/)) {
			    $prev_name = $game_name;
                $prev_num = $anum;
			}
		}
	}

	flock (GAMEFILE, $unlock);
	close(GAMEFILE);

	if ( ! $moved) {
		$game_title = $game_name;
	}
	
       $game_label = $game_number;

	if ( open ( GAMEFILE, "<" . $game_path)) {
	
		$start_line = 0;
		if ( $quick > 0)
		{
		    if ( $total_move_count > $quick) {
			    $start_line = $total_move_count - $quick;
		    }
            if ( $extend eq "all")
            {
                $start_line = 0;
            } 
		    elsif ( $extend > 0)
		    {
		        if ( $start_line >= $extend)
		        {
		            $start_line = $start_line - $extend;
		        }
		    }
		}
		if (( $start_line > 0) || ( $total_move_count > 12)) {
			print STDOUT "<FONT face=\"verdana,default\" size=2>\n";
			if ( $start_line > $base_extend) {
		        $tmp = "<A href=\"$script?$game_number\&$game_sizedefault&extend=" . ($extend + $base_extend) . "\">";
		        print STDOUT "$tmp<IMG hspace=8 border=0 src=\"${image_dir}yellowuparrow.gif\">&nbsp;Load $base_extend earlier moves</a><br>";
		    }
            if ( $start_line > 0) {
		        $tmp = "<A href=\"$script?$game_number\&$game_sizedefault&extend=all\">";
                print STDOUT "$tmp<IMG hspace=8 border=0 src=\"${image_dir}blueuparrow.gif\">&nbsp;See the full game</a><br>";
		    }
			print STDOUT "<A href=\"#bottom\">\n<IMG hspace=8 border=0 src=\"${image_dir}grndownarrow.gif\">&nbsp;Bottom of page</a>";
		    print STDOUT "</font>";
		}

		if ( $start_line > 0 ) {
		    print STDOUT "<P>The most recent moves...";
		}

		flock ( GAMEFILE, $exclusive_lock);

		print STDOUT "$list_open\n";

		$i = 0;
		while ( $user_line = <GAMEFILE>) {
			if ( $i++ >= $start_line) {
				chomp( $user_line);
				($move_time, $move_location, $user_name, $user_move, $user_colour) = split(/~/, $user_line);
				$user_name =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
				$user_move =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;

				if ( $user_colour ne "") {
					$user_colour =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
					$user_name = "<FONT color=\"$user_colour\">" . $user_name . "</font>";
				}

				$user_move =~ s/(\<\/*?)SCRIPT.*?(>)/$1XMP$2/gis;
				$user_move =~ s/(\<\/*?)IMG.*?(>)/[image]/gis;

				if ( $user_name eq "MC-REMARK") {
					print STDOUT "$list_close\nMC Server: $user_move\n$list_open";
				} elsif ( $user_name eq "MC-NARRATIVE") {
					print STDOUT "$list_close\n$narrative_open\n$user_move\n$narrative_close\n$list_open";
				} else {
					print STDOUT "$list_open_elem\n<B>$user_name:</b> $user_move</b></i>\n$list_close_elem";
				}
			}
		}

		flock (GAMEFILE, $unlock);
		close(GAMEFILE);
	} else {
		print STDOUT "<H3>There are no moves yet in this game</h3>\n";
	}

	print "$list_close\n<hr>\n";

	if (($game_state eq $stateArchived) && ( ! $game_won)) {
		print STDOUT "Game over! And what a splendid game it was, too.<br>\n";
	}

	print STDOUT "<FONT face=\"verdana,default\" size=2>\n";
    if (( $prev_num ne "") && ( $game_state ne $stateInvisible)) {
        $prev_name =~ s/<(.*?)>//g;
        print STDOUT "<A href=\"$script?$prev_num\&$game_sizedefault\"><IMG hspace=8 border=0 src=\"${image_dir}leftarrow.gif\">Previous: <B>$prev_name</b></a> &nbsp; ";
    }
    print STDOUT "<A href=\"$home_ref\">Home</a> &nbsp; ";
    
    if (( $next_num ne "") && ( $game_state ne $stateInvisible)) {
        $next_name =~ s/<(.*?)>//g;
        print STDOUT "<A href=\"$script?$next_num\&$game_sizedefault\">Next: <B>$next_name</b><IMG hspace=8 border=0 src=\"${image_dir}rightarrow.gif\"></a>\n";
    }
	print STDOUT "<P><A name=\"bottom\">$move_prompt</font>";

}

sub parse_form_data {
		if ( ! $ENV{'CONTENT_LENGTH'}) {
			return;
		}
		
       	local( *FORM_DATA) = @_;

       	local( $request_method, $post_info, @key_value_pairs,
       		$key_value, $key, $value);

       	read (STDIN, $post_info, $ENV{'CONTENT_LENGTH'});

       	@key_value_pairs = split (/&/, $post_info);

       	foreach $key_value (@key_value_pairs) {
       		($key, $value) = split (/=/, $key_value);
       		$value =~ tr/+/ /;

       		if ( defined($FORM_DATA{$key})) {
       			$FORM_DATA{$key} = join ("\0", $FORM_DATA{$key}, $value);
       		} else {
        		$FORM_DATA{$key} = $value;
        	}
       }

}
        
sub newGame {
		$FORM{'game_name'} =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
		($game_name, $winning_move) =  split( /~/, $FORM{'game_name'});
		$game_number = $FORM{"game_number"};
		$game_intro = $FORM{"game_intro"};
		($tmp_gamename = $game_name) =~ s/\s//eg;
        ($tmp_username = $user_name) =~ s/\s//eg;
    	$tmp_username =~ s/$lt(.*?)$gt//g;
        ($tmp_move = $user_move) =~ s/\s//eg;
        ($tmp_intro = $game_intro) =~ s/\s//eg;

# player must enter a name and either an intro or a move
	    if (( $tmp_gamename eq "") ||
	        ( $tmp_username eq "") ||
		    (( $tmp_move eq "") && ( $tmp_intro eq ""))) {
			return 0;
		}
		
		$game_name =~ s/<(\/?)font(.*?)>//gi;
		if ( open ( NEXTFILE, "+<" . $next_path)) {
			flock ( NEXTFILE, $exclusive_lock);
			$new_game = <NEXTFILE>;
			chomp( $new_game);
			if ( $new_game ne $game_number) { 
				flock ( NEXTFILE, $unlock);
				close(NEXTFILE);
				return 0;
			}
		} else {
			die "Could not open next game file $next_path\n";
		}

		if ( open ( GAMEFILE, ">>" . $full_path)) {
			flock( GAMEFILE, $exclusive_lock);
			print GAMEFILE "$game_number~$game_name~A~$winning_move\n";
			flock ( GAMEFILE, $unlock);
			close( GAMEFILE);
			seek (NEXTFILE, 0, 0);
			print NEXTFILE ($game_number+1);
		}
		flock ( NEXTFILE, $unlock);
		close( NEXTFILE);
		
		$total_move_count = 0;
		return 1;
}

sub getGame {
	open ( GAMEFILE, "<" . $full_path)
		|| die "Could not open requested game index file $full_path\n";
	flock ( GAMEFILE, $exclusive_lock);

	$game_count = 0;
	$active_count = 0;
	$revived = 0;
	$game_number = 0;
	while ( $user_line = <GAMEFILE>) {
		$user_line =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
		$user_line =~ s/[\n\r]//eg;
		if ( $user_line) {
			$game_count++;
			($game_number, $game_name, $game_state, $winning_move) =
				split( /~/, $user_line);
			if ( $game_number eq $game_req) {
				last;
			}
		}
	}
	flock ( GAMEFILE, $unlock);
	close ( GAMEFILE);

	$total_move_count = `wc -l $game_path`;
	$total_move_count += 0;

	return ( $game_number eq $game_req);
}

sub getDayTime {
	local($sec, $min, $hour, $day, $nmonth, $year, $wday, $yday, $isdst) =
   		gmtime( time);

        $time_string = sprintf("%02d-%02d-%02d-%02d-%02d-%02d-%02d-%02d",
       			    $wday, $yday, $day, $nmonth, $year, $hour, $min, $sec);


      	return ($time_string);
}

sub checkGameWon {

	$game_won = 0;

	if ( $game_state ne "A") {
		return $game_won;
	}


	($tmp_move = $user_move) =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;

	if ( $winning_move eq "") {
		$winning_move = $std_winning_move;
	}
	if ( $tmp_move =~ (m/<.*>$winning_move<.*>/is)) {
		
		$game_won = 1;
	}

	return ( $game_won);
}

sub updateActiveGames {
    
    if ( $game_state eq $stateInvisible) {
	return;
    }
        
	open ( MAINFILE, "+<" . $full_path)
		|| die "Could not open requested game index file $full_path\n";
		flock ( MAINFILE, $exclusive_lock);

		$game_count = 0;
		$revived = 0;
		$user_name =~ s/$lt(.*?)$gt//g;

		for ( $game_count = 0; $user_line = <MAINFILE>; $game_count++) {
		    chomp( $user_line);
			if ( $user_line) {
				($this_game_number, $this_game_name, $this_game_state, $this_winning_move) =
					split( /~/, $user_line);
				if ( $this_game_number eq $game_req) {
				    if ( $game_won) {
				        $this_game_state = "R";
				    }
				    
				    $game_entry[ $game_count++] = "$this_game_number~$this_game_name~$this_game_state~$this_winning_move~$user_name~$dayTime\n";

				} else {
				    $game_entry[ $game_count++] = $user_line . "\n";
				}
			}
		}

        truncate( MAINFILE, 0);

        seek( MAINFILE, 0, 0);
        
		for ( $i = 0; $i < $game_count; $i++ ) {
		    print MAINFILE $game_entry[ $i];
		}
		    
		flock ( MAINFILE, $unlock);
		close ( MAINFILE);
}

sub gameFailed {

	print STDOUT <<End_Of_FailedGame_Content;
Content-type: text/html

<HTML>
<HEAD>
<TITLE>
Mornington Crescent: Game Creation Failed
</title>
</head>
<BODY 
 bgcolor="$body_bgcolor"
 text="$body_text" 
 link="$body_link" 
 alink="$body_alink" 
 vlink="$body_vlink">

<font face="verdana,default">
<H2>Sorry!</h2>
<BLOCKQUOTE>
<BLOCKQUOTE>
Game not created. <br>
This page will be displayed under the following conditions:
<UL>
<LI>
You didn't enter a game name;
<LI>
You didn't enter your name;
<LI>
You didn't enter an opening move and/or an introduction;
<LI>
Someone got in ahead of you and created a game in the slot you were after 
(in which case there may be more available, feel free to try again);
<LI>
You entered the game creation URL manually and are just now finding 
out that the server will only create the game it's ready to.
</ul>
<P>
<A href="/mornington/">Return 
to the main page</a>. If you want.
</blockquote>
</blockquote>
</font>
</body>
</html>
End_Of_FailedGame_Content


}

sub invalidGame {

	print STDOUT <<End_Of_InvalidGame_Content;
Content-type: text/html

<HTML>
<HEAD>
<TITLE>
Mornington Crescent: Nonexistent Game
</title>
</head>

<BODY 
 bgcolor="$body_bgcolor"
 text="$body_text" 
 link="$body_link" 
 alink="$body_alink" 
 vlink="$body_vlink">

<font face="verdana,default">
<H2>Sorry!</h2>
<BLOCKQUOTE>
<BLOCKQUOTE>
Game not found.
<P>
You've requested game "$game_req", which is not recognised. If you 
reached this through a link on this server or are otherwise convinced
this is an error, please <A href="mailto:djp-buftoon@xenoplasm.com">mail the author</a>.
<P>
<A href="$main_script">Return to the main page</a>. If you want.
</blockquote>
</blockquote>
</font>
</body>
</html>
End_Of_InvalidGame_Content


}

sub badHTML
{

    $pairedTags =
        "|FONT|B|I|STRIKE|U|A|BLINK|H1|H2|H3|H4|H5|H6|SUB|SUP|CENTER|" .
        "BLOCKQUOTE|SMALL|EMP|STRONG|SCRIPT|TT|CODE|MARQUEE|TABLE|" .
        "PRE|TR|TD|UL|OL|IFRAME|ILAYER|";
    
    $move = $_ [0];    
    
    while ( $move =~ /\G.*?<([^> \t\r\n\f]+)(.*?)>/gis) {
       $tagAlone = $1;
       $argsQt = $2;
       if ( length( $argsQt)) {
            $argsQt =~ s/[^"]//g;
            if ( length( $argsQt) % 2) {
                return true;
            }
       }
        $tagAlone =~ s/(\/)//;
        if ( "$1" eq "/") {
            $tagSet =~ s/\|$tagAlone\|//i;
        } elsif ( $pairedTags =~ m/\|$tagAlone\|/i) {
            $tagSet = $tagSet . "|". $tagAlone . "|";
        }
    }
    return ( $tagSet ne "");
}

sub setPairs {
    $value_in = $_[ 0];
    @ary = split ( /\&/, $value_in);
    $i = 0;
    $game_req = 0;

    foreach $pair ( @ary)
    {
        if ( $pair > 0)
        {
            $game_req = $pair;
        }
        else
        {
            ($n, $v) = split ( /=/, $pair);
            if ( $n == 0)
            {
                $$n = $v;
            }
	    if ( $v == 0) {
		if ( $n eq "create") {
		    $game_action = $n;
		} elsif ( $n eq "quick") {
		    $quick = $quick_default;
		} elsif ( ! $game_req)  {
		    $game_req = $n;
		}
	    }
        }
    }

}

sub checkSecurity {
    $rmt_addr = $ENV{'REMOTE_ADDR'};

    $okay = 1;
    for $addr (@shitlist) {
        if ( $rmt_addr =~ m/^$addr/) {
            $okay = 0;
        }
    }

    $redirect = "";

    if ( ! $okay) {
        $auth = $ENV{HTTP_COOKIE};
        $auth =~ /AUTH=([^;]*)/;
        $auth = $1;

        if ( $auth eq $stdauth ) {
            $okay = 1;
        }
    }
    
    return( $okay);
}

sub checkReferer {
    $referer = $ENV{'HTTP_REFERER'};

    $okay = 1;
    for $addr (@badsource) {
        if ( $referer =~ m/$addr/) {
            $okay = 0;
        }
    }    
    return( $okay);
}


sub dispBlank {
    print STDOUT <<End_of_blank;
Content-type: text/html

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>404 Not Found</TITLE>
</HEAD><BODY>
<H1>Not Found</H1>
The requested URL was not found on this server.<P>
<HR>
<ADDRESS>Buftoon 150 Server at crulmtrex.com Port 80</ADDRESS>
</BODY></HTML>
End_of_blank

}


