#!/usr/bin/perl

require "bc_setup.cgi";
require "bc_color.cgi";
require "bc_lock.cgi";

print "Content-type: text/html\nPragma: no-cache\n\n";

# get the form data.
&get_form_data;

# check for room, and read the old message file
$formdata{'room'} =~ s/\W//g;
$formdata{'room'} = lc($formdata{'room'});

&lock($chatpath . '/' . $formdata{'room'} . '.lck');

# create room if not exist.
if (!(-e "$chatpath/$formdata{'room'}\.htm")) {
  open(CREATE, ">$chatpath/$formdata{'room'}\.htm");
  close(CREATE);
}

open(HTMLOLD, "$chatpath/$formdata{'room'}\.htm") ||
  &myerror("Невозможно открыть комнату: $formdata{'room'}");
@lines=<HTMLOLD>;
close(HTMLOLD);

# time message printed.
my $thetime = time;

# write and output new messages file
          $newmessage = '';
	      if (($formdata{'cname'} ne '') && ($formdata{'message'} ne '')){
		    $ColoredName = $formdata{'cname'};
            $ColoredMessage = $formdata{'message'};
			# replace smilely faces
			$ColoredMessage =~ s/\:\)/\<img src=\"$imagedir\/smile1.gif\" width=\"16\" height=\"12\" border=\"0\"\>/g;
			$ColoredMessage =~ s/\:\(/\<img src=\"$imagedir\/smile2.gif\" width=\"16\" height=\"12\" border=\"0\"\>/g;
			$ColoredMessage =~ s/\;\)/\<img src=\"$imagedir\/smile3.gif\" width=\"16\" height=\"12\" border=\"0\"\>/g;
			# check for me action
            if ($ColoredMessage =~ s/^\.me//i) {
              $ColoredName = &Make_Color('`1|||`4|||`1|||`% ' . $ColoredName);
			  $ColoredMessage = &Make_Color('<b>`2' . $ColoredMessage . '</b>');
            } else {
			   $ColoredName = &Make_Color($ColoredName . '`%:');
			   $ColoredMessage = &Make_Color($ColoredMessage);
			  }

			$newmessage = "<FONT SIZE=\"-1\"><B>$ColoredName</B> $ColoredMessage<!--$thetime//--></FONT><BR>\n";
          }
		
		open (NEW, ">$chatpath/$formdata{'room'}\.htm");
		print NEW "<HTML><HEAD><META HTTP-EQUIV=\"Refresh\" CONTENT=\"$ChatRefresh\">\n";
		print NEW "</HEAD><BODY BGCOLOR=\"#F0F0F0\">\n";
		print NEW "<a target=_top
href=\"http://top.list.ru/jump?from=37448\"><script language=\"JavaScript\"><!--
d=document;js=10;a=';r='+escape(d.referrer)
//--></script><script language=\"JavaScript1.1\"><!--
js=11;a+=';j='+navigator.javaEnabled()
//--></script><script language=\"JavaScript1.2\"><!--
js=12;s=screen;a+=';s='+s.width+'*'+s.height
a+=';d='+(s.colorDepth?s.colorDepth:s.pixelDepth)
//--></script><script language=\"JavaScript1.3\"><!--
js=13//--></script><script language=\"JavaScript\"><!--
d.write('<img src=\"http://top.list.ru/counter'+
'?id=37448;t=41;js='+js+a+'\" alt=\"TopList\" '+
'border=0 height=31 width=88>')
if(js>11)d.write('<'+'!-- ')//--></script><noscript><img
src=\"http://top.list.ru/counter?js=na;id=37448;t=41\"
border=0 height=31 width=88
alt=\"TopList\"></a>
<a target=_top
href=\"http://top.list.ru/jump?from=37448\"></noscript><script language=\"JavaScript\"><!--
if(js>11)d.write('--'+'>')
//--></script></a> 
		<!--TopList COUNTER-->\n";
		print "<HTML><HEAD><META HTTP-EQUIV=\"Refresh\" CONTENT=\"$ChatRefresh;URL=$chaturl/$formdata{'room'}\.htm\">\n";
		print "</HEAD><BODY BGCOLOR=\"#F0F0F0\">\n";	
			if ($newmessage ne '') {
			  print NEW $newmessage;
			  print $newmessage;
			}

			for ($i = 1; $i < $MaxChatLines; $i++)
			{
			    $lines[$i] =~ m/<!--(\d*)\/\/-->/;
				if ((time - $1) <= $ChatMessageTime)
				{
				  if ($lines[$i] ne "</BODY></HTML>\n") {
			        print NEW "$lines[$i]";
			        print "$lines[$i]";
				  }
				}
			}
			print NEW "</BODY></HTML>\n";
			print "</BODY></HTML>\n";
		close(NEW);

unlock($chatpath . '/' . $formdata{'room'} . '.lck');
exit;

# Gets Form data, also removes html formatting.
sub get_form_data {
	if ($ENV{'REQUEST_METHOD'} eq 'GET') {
      @pairs = split(/&/, $ENV{'QUERY_STRING'});
    }
	else
	{	
	$buffer = "";
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs=split(/&/,$buffer);
    }

	foreach $pair (@pairs)
	{
		@a = split(/=/,$pair);
		$name=$a[0];
		$value=$a[1];
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$value =~ s/~!/ ~!/g;
		$value =~ s/\+/ /g;
		$value =~ s/\</\&lt\;/g;  # remove to enable html tags in messages.
		$value =~ s/\>/\&gt\;/g;  # remove to enable html tags in messages.
		$value =~ s/\r//g;
		push (@data,$name);
		push (@data, $value);
	}
	%formdata=@data;
	%formdata;
}

sub myerror {
   my $msg = shift;
   &unlock($chatpath . '/' . $formdata{'room'} . '.lck');
   print $msg;
   exit;
}
