#!/usr/bin/perl
&ReadParse(*regdata);

if ($regdata{'action'} eq 'getbanner')
{
  print "Content-type: text/html\nPragma: no-cache\n\n";
}
else
{
  print "Content-type: text/text\nPragma: no-cache\n\n";
}

#print "action:";
#print "user:" . $regdata{'user'} ."\n";
#print "chatfile:" . $regdata{'chatfile'} ."\n";
#print "action:" . $regdata{'action'} ."\n";
#print "line:" . $regdata{'line'} ."\n";
#print "userfile:" . $regdata{'userfile'} ."\n";
$delimit = "^#^";

$datapath = $regdata{'datadir'};
$chatfile = $datapath . $regdata{'chatfile'}; 
$userfile = $datapath . $regdata{'userfile'}; 
$userfile2 = $datapath . $regdata{'userfile'}  . '2';
$callfile = $datapath . $regdata{'callfile'}; 


if ($regdata{'action'} eq 'get' )
{

  unless (open (DataFile, $chatfile)) 
  {
#     print ("cant open file1: ", $chatfile, "\n");
     create_file($chatfile, "");
     die ("cant open  file $chatfile\n");
  }
 
 
  @lines = <DataFile>;
  close DataFile; 
  $lineNum = 0 + $regdata{'linenum'};   


 
  $firstLine = -1;
#print ("enter get in cgi  lineNum=", $lineNum, "   #lines=",  "$#lines", "\n"); 

  for ($kk=$#lines-1; $kk>-1 && $firstLine==-1; $kk--)
  {
     chop($lines[$kk]);
     @LLL = split (/\^\#\^/, $lines[$kk]);
     $curNum = 0 + $LLL[0];
#print ("enter get in cgi lineNum=",  "$lineNum", "  curNum=", "$curNum", "\n");   
     if ($lineNum > $curNum)
     {
#print ("in if\n");
       $firstLine = $kk + 2;
      
     }
   }

   for ($kk=$firstLine; $kk<=$#lines; $kk++)
   {
      print ($lines[$kk], "\n");

   }

   if ($kk == $firstLine && ! $kk<=$#lines)
   {
      print ("###***^^^", "\n");
   }
  
   return;
  
}

if ($regdata{'action'} eq 'updateuser' )
{
   `cp $userfile2 $userfile`;
   `rm $userfile2`;

   print "###***^^^";
   return;
}


if ($regdata{'action'} eq 'getlines' )
{


  if ($regdata{'option'} eq 'updateuser' )
  {
    unless (open (DataFile, $userfile2)) 
    {
      unless (open (DataFile, ">" . $userfile2)) 
      {
        print ("cant open file6: ", $userfile2, "\n");
        return;
      }
      $tt = $regdata{'user'} . $delimit . $regdata{'email'} . "\n";
      print DataFile ($tt);
      close DataFile;
      print "###***^^^";
      return;
      
    }
    @lines = <DataFile>;
    close DataFile;

    unless (open (DataFile, ">" . $userfile2)) 
    {
      print ("cant open file6: ", $userfile2, "\n");
      return;
    }
#print ("#### IN CGI: after open userfile lines=", $#lines, "\n");  
  
    $UserExist = 0;
    for ($i=0; $i<=$#lines; $i++)
    {
      @tt = split(/\^\#\^/,$lines[$i]);
#print ($tt[0], "***", $regdata{'user'}, "***");
      print DataFile ($lines[$i]);
      if ($tt[0] eq $regdata{'user'})
      { 
        $UserExist = 1;
      }
    }
 
    if ($UserExist == 0)
    {
      
       $tt = $regdata{'user'} . $delimit . $regdata{'email'} . "\n";
       print DataFile ($tt);
    }
    close DataFile;
  }


  $TheFile = $datapath . $regdata{'file'}; 

#print ( "enter getuser ... in cgi");
   unless (open (DataFile, $TheFile)) 
   {
     die ("cant open  file\n");
   }
   @lines = <DataFile>;
   close DataFile;

   for ($i=0; $i<=$#lines; $i++)
   {
     print $lines[$i];
   }

   print "###***^^^";
   return;
  
}

if ($regdata{'action'} eq 'getnews')
{

  @Files = `ls $regdata{'newsdir'}`;

  srand(time ^ $$);
  $ttt = $Files[int rand $#Files];

  $FileName = $regdata{'newsdir'} . $ttt;
    unless (open (DataFile, $FileName)) 
    {
      print ("cant open: ", $$ttt, "\n");
      return;
    }
     
    @lines = <DataFile>;
    close DataFile;

  for ($i=0; $i<=$#lines; $i++)
  {
    print $lines[$i];
  }

  print "###***^^^";
  return;
}


if ($regdata{'action'} eq 'join')
{
#print ( "enter join ... in cgi");
  $user_exist = 0;
  $file_exist = 0;
  $lineNum = -1;
  if (open (DataFile2, $userfile)) 
  {
    $file_exist = 1;
    $lines = <DataFile2>;
    while ($lines ne "")
    {
      @tt = split(/\^\#\^/,$lines);
#print ($tt[0], "****", $regdata{'user'}, "****", $file_exist);
      if ($tt[0] eq $regdata{'user'})
      {
#print ($tt[0], "****", $regdata{'user'}, "****", $file_exist);
        $user_exist = 1;
      }

      $lines = <DataFile2>;
    }

    close DataFile2;
  }
  else
  {
     create_file($userfile, "");
     
  }



  if ($user_exist >0)
  {
    $lineNum = -100;
    print "$lineNum";
    return;
  }

       
  $tt = $regdata{'user'} . $delimit . $regdata{'email'} . "\n";
  

  if (!open (DataFile, ">>$userfile"))
    {
        print ("cant open file4: ", $userfile, "\n");
        return;
    }


  print DataFile  $tt;
  close DataFile;

  if (!open (DataFile, "$chatfile"))
  {
        $lineNum = -1;
  }
  else
  {
    @lines = <DataFile>;
    close DataFile; 
    @List = split (/\^\#\^/, $lines[$#lines]);
    $lineNum = 1 + $List[0];   
#print ("$lineNum=", $lineNum, "\n");

  }


    print ("$lineNum", "\n");
   
}


if ($regdata{'action'} eq 'put' || $regdata{'action'} eq 'join' || $regdata{'action'} eq 'leave' || $regdata{'action'} eq 'sys')
{
#print ( "enter put ... in cgi");
  $LN = -1;
  if (open (DataFile, $chatfile))
  {
    @lines = <DataFile>;
    close DataFile;      
    if ($#lines>0)
    {
      $LN = 1 + $#lines;
    }
    else
    {
      $LN = $#lines;
    }

    if ($regdata{'action'} eq 'join' || $regdata{'action'} eq 'leave')
    {
	$tt = $LN . $delimit . 'System' . $delimit . $regdata{'line'} . "\n";
    }
    elsif ($regdata{'action'} eq 'sys' )
    {
	$tt = $LN . $delimit . 'News' . $delimit . $regdata{'line'} . "\n";
    }
    else
    {
  	$tt = $LN . $delimit . $regdata{'user'} . $delimit . $regdata{'line'} . "\n";
    }
  }

  unless (open (DataFile, ">>" . $chatfile)) 
  {
 #    print ("cant open file3: ", $chatfile, "\n");
     die ("cant open  file\n");
  }
#  print "Result from CGI:" .  $tt;
  print DataFile  $tt;
  close DataFile;

# print "output:" . $tt;
  if ($regdata{'action'} eq 'join')
  {
     return;
  }
  print "###***^^^";
}

if ($regdata{'action'} eq 'getbanner')
{
#print ( "enter getbaner ... in cgi");
  if ($regdata{'action2'} eq 'getgraph')
  {
    $bannerfile = $regdata{'imagedir'} . $regdata{'imageinfo'}; 
    unless (open (DataFile, $bannerfile)) 
    {
     print ("cant open  file :", $bannerfile, "\n");
     die ("cant open  file $bannerfile\n");
    }
  
  
    @input = <DataFile>;
    close(DataFile);
    srand(time ^ $$);

    $LastWall = $#input;
    $ttt = $input[int rand $LastWall];
    chop($ttt);
    @List = split (/\^\#\^/, $ttt);

print <<"EOP" ;  
<html><body>
<center>
<a href="$List[1]" target = "_blank"><img src="$List[0]" border=0 width=550 height=100></a>
</center>
EOP

if ($List[2] ne "" && $regdata{'sound'} eq "1")
{
print <<"EOP" ; 
<BGSOUND SRC="$List[2]">
<EMBED SRC="$List[2]" AUTOSTART="TRUE" HIDDEN="TRUE" LOOP="TRUE">
EOP

}
}
else
{

print <<"EOP" ;  
<html><body>
<center>
$regdata{'text'}
</center>
EOP

}

print <<"EOP" ;  
</body></html>
EOP


  
}

elsif ($regdata{'action'} eq 'check' )
{
#print ( "enter check in cgi");
  $user_exist = 0;
  if (open (DataFile2, $userfile)) 
  {
    $lines = <DataFile2>;
    while ($lines ne "")
    {
      @tt = split(/\^\#\^/,$lines);
#print ($tt[0], "****", $regdata{'user'}, "****");
      if ($tt[0] eq $regdata{'user'})
      {
        $user_exist = 1;
        print "notok";
        close DataFile2;
        return;
      }

      $lines = <DataFile2>;
    }

    close DataFile2;
  }



    print "ok";
    return;
  
}
elsif ($regdata{'action'} eq 'getCaller' )
{

#print ( "enter getCaller ... in cgi");
   unless (open (CallFile, $callfile)) 
   {
    # print ("cant open file4.5: ", $callfile, "\n");
     create_file($callfile, "");
     die ("cant open  file\n");
   }
   @lines = <CallFile>;
   close CallFile;

   unless (open (CallFile, ">" . $callfile)) 
   {
#     print ("cant open file5.8: ", $callfile, "\n");
     return;
   }

   for ($i=0; $i<=$#lines; $i++)
   {

    chop($lines[$i]);
    @tt = split(/\^\#\^/,$lines[$i]);
#print ("tt[0]:", $tt[0], "**\n");
#print ("regdata{'user'}:", $regdata{'user'}, "**\n");
#print ("tt[1]:", $tt[1], "**\n");


    if ($tt[1] eq $regdata{'user'})
    {
      
      if ($tt[2] ne "read")
      {
        print CallFile ($tt[1], "^#^", $tt[0], "^#^", "read\n");
        print ($tt[0], "\n");
      }
      else
      {
        print ($tt[0], " Replied and \n");
      }
    }
    else
    {
      print CallFile ($lines[$i], "\n");
    }
  }
  close CallFile;  
  print "###***^^^";
  return;
  
}
elsif ($regdata{'action'} eq 'getCallee' )
{
#print ( "enter getCallee ... in cgi");
   unless (open (CallFile, $callfile)) 
   {
   #  print ("cant open file4.5: ", $callfile, "\n");
     create_file($callfile, "");
     die ("cant open  file\n");
   }
   @lines = <CallFile>;
   close CallFile;

   for ($i=0; $i<=$#lines; $i++)
   {

    @tt = split(/\^\#\^/,$lines[$i]);
#print ("tt[0]:", $tt[0], "**\n");
#print ("regdata{'user'}:", $regdata{'user'}, "**\n");
#print ("tt[1]:", $tt[1], "**\n");


    if ($tt[0] eq $regdata{'user'})
    {
      print ($tt[1], "\n");
    }
  }
  print "###***^^^"; 
  return;
  
}
elsif ($regdata{'action'} eq 'addCall' )
{
#print ( "enter addCall ... in cgi");
   unless (open (CallFile, $callfile)) 
   {
     print ("cant open file4.5: ", $callfile, "\n");
     create_file($callfile, "");
     die ("cant open  file\n");
   }
   @lines = <CallFile>;
   close CallFile;


   for ($i=0; $i<=$#lines; $i++)
   {
     chop($lines[$i]);
    if ($lines[$i] eq $regdata{'line'})
    {
      print "###***^^^";
      return;
    }
   }

   unless (open (CallFile, ">>" . $callfile)) 
   {
     print ("cant open file5.8: ", $callfile, "\n");
     return;
   }

   print CallFile ($regdata{'line'}, "\n");
   close CallFile;
  return;
  
}
elsif ($regdata{'action'} eq 'delCall' )
{
#print ( "enter delCall ... in cgi");
   unless (open (CallFile, $callfile)) 
   {
     create_file($callfile, "");
     print ("cant open file4.7: ", $callfile, "\n");
     die ("cant open  file\n");
   }
   @lines = <CallFile>;
   close CallFile;


  
   unless (open (CallFile, ">" . $callfile)) 
   {
     print ("cant open file5.8: ", $callfile, "\n");
     return;
   }

   for ($i=0; $i<=$#lines; $i++)
   {
    chop($lines[$i]);
    if ($lines[$i] ne $regdata{'line'})
    {
      print CallFile ($lines[$i], "\n");
    }
   }

   
   close CallFile;
  print "###***^^^";
  return;
  
}
elsif ($regdata{'action'} eq 'leave' )
{
#print ( "enter leave ... in cgi");
  unless (open (DataFile, $userfile)) 
  {
     print ("cant open file5: ", $userfile, "\n");
     die ("cant open  file\n");
  }
  @lines = <DataFile>;
  close DataFile;

  unless (open (DataFile1, ">" . $userfile)) 
  {
     print ("cant open file6: ", $userfile, "\n");
     return;
  }
#print ("#### IN CGI: after open userfile lines=", $#lines, "\n");  
  
  for ($i=0; $i<=$#lines; $i++)
  {
    @tt = split(/\^\#\^/,$lines[$i]);
#print ($tt[0], "***", $regdata{'user'}, "***");
    if ($tt[0] ne $regdata{'user'})
    {
      print DataFile1 ($lines[$i]);
    }
  }
  close DataFile1;


}

sub create_file {
  local ($FileName, $TheContent) = @_;

  unless (open (TheFile,
            ">$FileName")) 
  {
     print ("cant open File:", $FileName, "\n");
     die ("cant open EnvFile\n");
  }

  print TheFile $TheContent;
  close TheFile;

  `chmod 777 $FileName`;
}



  


sub ReadParse {
  local (*in) = @_ if @_;
  local ($len, $type, $meth);

  # Get several useful env variables
  $type = $ENV{'CONTENT_TYPE'};
  $len = $ENV{'CONTENT_LENGTH'};
  $meth = $ENV{'REQUEST_METHOD'};

  if ($len > $cgi_lib'maxdata) {
      &CgiDie("cgi-lib.pl: Request to receive too much data: $len bytes\n");
  }

  if ($type eq 'application/x-www-form-urlencoded' || $type eq '' ) {
    local ($key, $val, $i);

    # Read in text
    if ($meth eq 'GET') {
      $in = $ENV{'QUERY_STRING'};
    } elsif ($meth eq 'POST') {
        read(STDIN, $in, $len);
    } else {
      &CgiDie("cgi-lib.pl: Unknown request method: $meth\n");
    }

    @in = split(/[&;]/,$in); 

    foreach $i (0 .. $#in) {
      # Convert plus to space
      $in[$i] =~ s/\+/ /g;

      # Split into key and value.  
      ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.

      # Convert %XX from hex numbers to alphanumeric
      $key =~ s/%(..)/pack("c",hex($1))/ge;
      $val =~ s/%(..)/pack("c",hex($1))/ge;

      # Associate key and value
      $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
      $in{$key} .= $val;
    }

  } elsif ($ENV{'CONTENT_TYPE'} =~ m#^multipart/form-data#) {
    # for efficiency, compile multipart code only if needed
eval <<'END_MULTIPART';
{
    local ($buf, $boundary, $head, $blen);
    local ($bpos, $lpos, $left, $amt, $fn, $ser);
    local ($bufsize, $maxbound, $writefiles) = 
      ($cgi_lib'bufsize, $cgi_lib'maxbound, $cgi_lib'writefiles);

    ($boundary) = $type =~ /boundary="([^"]+)"/; #";   # find boundary
    ($boundary) = $type =~ /boundary=(\S+)/ unless $boundary;
    &CgiDie ("Boundary not provided") unless $boundary;
    $boundary =  "--" . $boundary;
    $blen = length ($boundary);

    if ($ENV{'REQUEST_METHOD'} ne 'POST') {
      &CgiDie("Invalid request method for  multipart/form-data: $meth\n");
    }

    if ($writefiles) {
      local($me);
      stat ($writefiles);
      $writefiles = "/tmp" unless  -d _ && -r _ && -w _;
      ($me) = $0 =~ m#([^/]*)$#;
      $writefiles = "$writefiles/$me";
    }

    $left = $len;
   PART: # find each part of the multi-part while reading data
    while (1) {
      $amt = ($left > $bufsize+$maxbound-length($buf) 
	      ?  $bufsize+$maxbound-length($buf): $left);
      read(STDIN, $buf, $amt, length($buf));
      $left -= $amt;

      $in{$name} .= "\0" if defined $in{$name}; 
      $in{$name} .= $fn if $fn;
     BODY: 
      while (($bpos = index($buf, $boundary)) == -1) {
        if ($name) {  # if no $name, then it's the prologe -- discard
          if ($fn) { print FILE substr($buf, 0, $bufsize); }
          else     { $in{$name} .= substr($buf, 0, $bufsize); }
        }
        $buf = substr($buf, $bufsize);
        $amt = ($left > $bufsize ? $bufsize : $left);
        read(STDIN, $buf, $amt, $maxbound);  # $maxbound == length($buf);
        $left -= $amt;
      }
      if (defined $name) {  # if no $name, then it's the prologe -- discard
        if ($fn) { print FILE substr($buf, 0, $bpos-2); }
        else     { $in {$name} .= substr($buf, 0, $bpos-2); } # kill last \r\n
      }
      close (FILE);
      last PART if substr($buf, $bpos + $blen, 4) eq "--\r\n";
      substr($buf, 0, $bpos+$blen+2) = undef;
      $amt = ($left > $bufsize+$maxbound-length($buf) 
	      ? $bufsize+$maxbound-length($buf) : $left);
      read(STDIN, $buf, $amt, length($buf));
      $left -= $amt;


      undef $head;  undef $fn;
     HEAD:
      while (($lpos = index($buf, "\r\n\r\n")) == -1) { 
        $head .= substr($buf, 0, $bufsize);
        $buf = substr($buf, $bufsize);
        $amt = ($left > $bufsize ? $bufsize : $left);
        read(STDIN, $buf, $amt, $maxbound);  # $maxbound == length($buf);
        $left -= $amt;
      }
      $head .= substr($buf, 0, $lpos+2);
      push (@in, $head);
      ($name) = $head =~ /name="([^"]+)"/; #"; 
      ($name) = $head =~ /name=(\S+)/ unless $name;  
      if ($writefiles && $head =~ /filename=/) {
        $ser++;
	$fn = $writefiles . ".$$.$ser";
	open (FILE, ">$fn") || &CgiDie("Couldn't open $fn\n");
      }
      substr($buf, 0, $lpos+4) = undef;
    }

}
END_MULTIPART
  } else {
    &CgiDie("cgi-lib.pl: Unknown Content-type: $ENV{'CONTENT_TYPE'}\n");
  }

  return scalar(@in); 
}

sub PrintHeader {
  return "Content-type: text/html\nPragma: no-cache\n\n";
}

# CgiDie
# Identical to CgiError, but also quits with the passed error message.

sub CgiDie {
  local (@msg) = @_;
  &CgiError (@msg);
  die @msg;
}

sub CgiError {
  local (@msg) = @_;
  local ($i,$name);

  if (!@msg) {
    $name = &MyURL;
    @msg = ("Error: script $name encountered fatal error");
  };

  print &PrintHeader;
  print "<html><head><title>$msg[0]</title></head>\n";
  print "<body><h1>$msg[0]</h1>\n";
  foreach $i (1 .. $#msg) {
    print "<p>$msg[$i]</p>\n";
  }
  print "</body></html>\n";
}


