#!/usr/bin/perl -w
#use strict;

use CGI::Carp qw(fatalsToBrowser);

# (c) NueDream Inc. 2000-2002 (www.nuedream.com)

##############    GLOBAL CONSTANTS    ############

my $file = "questions.db";    # This is the name of your questions file.
my $quizname =
  "Тестирование знаний";  # This is what appears in the TITLE.
my $spacer = '|';    # The delimeter used in the database.
my $result1 = "Ваша оценка: неудовлетворительно."
  ;                  # Message Displayed when user gets below 50%.
my $result2 = "Ваша оценка: удовлетворительно."
  ;                  # Message Displayed when user gets between 51%-80%.
my $result3 = "Ваша оценка: хорошо.";      # Message Displayed when user get above 80%.
my $result4 = "Ваша оценка: отлично.";    # Message Displayed when user get above 80%.
my $cheater = "Cheating won't get you anywhere in life."
  ;                                 # Message Displayed when user cheated.
my $fontface = "verdana, tahoma, arial";    # Font Type.
my $anticheat = 1;    # Enables or disables the anti-cheating feature
                      # (1-Enabled, 0-Disabled).
##############   PROGRAM START    ############

my @pairs = split( /&/, $ENV{'QUERY_STRING'} );
foreach my $pair (@pairs) {
	my ( $name, $value ) = split( /=/, $pair );
	if ($value) {
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("c", hex($1))/eg;
		$value =~ s/\n/ /g;
		$value =~ s/\r//g;
		$value =~ s/\cM//g;
	}
	$GET{$name} = $value;
}

my $cookie = $ENV{'HTTP_COOKIE'};
my @cookies = $cookie ? split( /;/, $cookie ) : "";

my $content = $ENV{'QUERY_STRING'};
my ( $type, $question ) = split( /=/, $content );

$question = 1 unless $question;

my $current = $question - 1;
my $correct = 0;

my $action = $GET{'action'};
unless ($action) {

	print <<HEADER;
Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//RU" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>$quizname</title>
<link href="../main.files/test.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../favicon.ico" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">

html, body, ul, ol, li, p, h1, h2, h3, h4, h5, h6, form, fieldset, a, img {
    font-family: "Times New Roman", Times, serif;
}
.style1 {
    font-size: large;
}
.style2 {
    text-align: center;
}

</style>
</head>
<body class="twoColFixLt">
    <div class="background_layer">
	<div id="container">

	    <div class="background_layer2">
		<div align="center">
		    <div style="text-align:center; font-size: 24pt;"><img src="../titles/title_solarsystem.jpg" alt="Солнечная система" width="950" height="100" longdesc="../titles/title_solarsystem.jpg" /></div>
		 </div>
		<div style="text-align:center;"></div>
		    <table style="border: 0px; width: 800px; height: 300px;">
			<tr>
			    <td style="width: 220px; vertical-align: top; padding-top: 30px;"><img src="Solar_system.jpg" alt="Солнечная система" width="216" height="162" longdesc="Solar_system.jpg"/></td>
				<td style="vertical-align: top; padding-left: 25px;">

HEADER

	open( DATA, $file ) or dienice("Couldn't open $file :: $!\n");

	#flock(DATA,0); # uncomment this line if using unix based server
	seek( DATA, 0, 0 );
	my @data = <DATA>;
	close(DATA);

	# Calculating total number of questions.
	my $total = 0;
	foreach my $line (@data) {
		my ( $quiz, $num, $q, $ans, $a, $b, $c, $d, $e, $f, $reason ) =
		  split( /\|/, $line );
		if ( $quiz eq $type ) {
			$total++;
		}
	}

	$total++;

	# Printing Quiz results.
	if ( $question == $total ) {

		print "<br><h3>Результат теста: ";
		foreach my $part (@cookies) {
			if ( $part =~ /$type/ ) {
				my ( $name, $value ) = split( /=/, $part );
				my @answers = split( /-/, $value );

				foreach my $a (@answers) {
					my ( $questionc, $answerc ) = split( /_/, $a );

					foreach my $line (@data) {
						chomp($line);
						my (
							$quiz, $num, $q, $ans, $a, $b,
							$c,    $d,   $e, $f,   $reason
						) = split( /\|/, $line );
#####################################################################
						if ( $quiz eq $type && $questionc eq $num ) {
							if ( substr( $answerc, 0, 1 ) eq $ans ) {
								my $tempa = substr( $answerc, 0, 1 );
								my $tempb = substr( $answerc, 1, 1 );

#								print
#"<b>$questionc.</b> $q<br>Ваш ответ: <b>$tempa</b>. <font color=\"#33cc00\"><b>Правильно!</b></font><ol>$reason</ol>";
								$correct++;
							}
							else {
								my $tempa = substr( $answerc, 0, 1 );
								my $tempb = substr( $answerc, 1, 1 );

#								print
#"<b>$questionc.</b> $q<br>Ваш ответ: <b>$tempa</b>. <font color=\"red\"><b>Неправильно!</b></font><br>Правильный ответ: <b>$tempb</b>.<ol>$reason</ol>";
							}
						}
					}
				}
			}
		}

		#	print "</font>";
		#	print "<br><hr width=\"450\" align=\"left\" color=\"black\" NOSHADE>";

		my $percent = $current ? ( $correct / $current ) * 100 : 0;

		#		printf( "<b>$correct</b> / <b>$current</b> = <b> %4.1f",
		#			$percent, "%</b><br><br>" );
		#		print "%</b><br><br>";
		printf( "%4.1f\%", $percent );
		print
"</h3><hr width=\"450\" align=\"left\" color=\"black\" NOSHADE><br>";
		print "<h3>";

		if ( ( $correct / $total ) <= 0.5 ) {
			print "$result1";
		}
		elsif ( ( $correct / $total ) <= 0.75 ) {
			print "$result2";
		}
		elsif ( ( $correct / $total ) <= 0.99 ) {
			print "$result3";
		}
		elsif ( ( $correct / $total ) <= 1.0 ) {
			print "$result4";
		}
		else {
			print "$cheater";
		}
		print "</h3>";

	}
	else {

		foreach my $line (@data) {
			chomp($line);
			my ( $quiz, $num, $q, $ans, $a, $b, $c, $d, $e, $f, $reason ) =
			  split( /\|/, $line );

			if ( $quiz eq $type && $question eq $num ) {

				print
"<form action=\"quiz.cgi?$type=$question&action=check\" method=\"GET\">\n";
				print "<br><b>$q</b><br>";

				if ( $a ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"a\" checked>1. $a<br>\n";
				}
				if ( $b ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"b\">2. $b<br>\n";
				}
				if ( $c ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"c\">3. $c<br>\n";
				}
				if ( $d ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"d\">4. $d<br>\n";
				}
				if ( $e ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"e\">5. $e<br>\n";
				}
				if ( $f ne "" ) {
					print
"<input type=\"radio\" name=\"$num\" value=\"f\">6. $f<br>\n";
				}

				print
				  "<br><input type=\"hidden\" name=\"$type\" value=\"$num\">\n";
				print
"<br><input type=\"hidden\" name=\"action\" value=\"check\">\n";
				print
"<input type=\"submit\" value=\"Продолжить…\">\n</form>\n";
			}
		}
	}

	print <<TAILER;
			    </td>
			</tr>
                    </table>
		    <p>&nbsp;</p>
		</div>
	    </div>
	</div>
    </div>
</body>
</html>
TAILER

}
elsif ( $GET{'action'} eq "check" ) {

	my $content = $ENV{'QUERY_STRING'};
	my ( $temp, $temp2, $temp3 ) = split( /&/, $content );
	my $answer;
	( $question, $answer ) = split( /=/, $temp );
	my ( $type,  $question ) = split( /=/, $temp2 );
	my ( $temp4, $act )      = split( /=/, $temp3 );

	my $start = $question + 1;
	my $url   = "quiz.cgi?$type=$start";
	my $tempv = "";

	my @cookies = split( /;/, $ENV{'HTTP_COOKIE'} );

	foreach my $crum (@cookies) {
		my ( $name, $value ) = split( /=/, $crum );
		if ( $name =~ /$type/ ) {
			$tempv = $value;
			last;
		}
	}

	open( DATA, $file ) or dienice("Couldn't open $file :: $!\n");
	flock( DATA, 0 );    # uncomment this line if using unix based server
	seek( DATA, 0, 0 );
	my @data = <DATA>;
	close(DATA);

	foreach my $line (@data) {
		chomp($line);
		my ( $quiz, $num, $q, $ans, $a, $b, $c, $d, $e, $f, $reason ) =
		  split( /\|/, $line );
		if ( $quiz eq $type && $question eq $num ) {
			if ( $tempv ne "" ) {
				if ( $tempv =~ /$question/ ) {
					if ( $anticheat == 1 ) {
						print "Content-type: text/html; charset=utf-8\n\n";
						print
"<br><br><center><font face=\"verdana\" size=\"2\"><b>$cheater</b><br><br>If you did not try to cheat, try again. This time do not double click the next button.<br> Click once and wait until the next question is fully displayed before clicking again.</font></center>";
					}
					else {
						print "Location: $url\n\n";
					}
				}
				else {
					my $tempcookie =
					  "$tempv" . "-" . $question . "_" . $answer . $ans;
					print "Set-cookie: $type=$tempcookie\n";
					print "Location: $url\n\n";
				}
			}
			else {
				my $tempcookie = $question . "_" . $answer . $ans;
				print "Set-cookie: $type=$tempcookie\n";
				print "Location: $url\n\n";
			}
		}
	}

}

#############    DYING SUBROUTINE    ############

sub dienice {
	my ($msg) = @_;
	print("<br><hr><br><h1>FATAL ERROR</h1><hr><br>\n");
	print($msg);
	exit;
}
