#!/usr/bin/perl

use CGI::Carp qw(fatalsToBrowser);

require "./admin/beallit.pl";
require "./admin/szavazogepadmin.lib.pl";

  &parse_input;
  &parse_cookie;
  
  @badfile_ext = qw(.cgi .jpg .jpeg .gif);
    
  &check_file_ext(@badfile_ext, $FORM{'form'});
 

  if ($check_ids =~ /yes/i) {
  
      @IDs = &get_array("$FullPath/$IdListPath");

      &check_ids($FORM{'id'}, @IDs);
  }
  

  &create_dir("$FullPath/$DATFLE/$FORM{'id'}");
    
  $CMTFLE   = "$FullPath/$DATFLE/$FORM{'id'}/comments.txt"; 
  $RATNGS   = "$FullPath/$DATFLE/$FORM{'id'}/ratings.txt";
 
  
  if (!-e $RATNGS) {
      
      &create_format_file($RATNGS, $voting_scale);
  
  }  
  
  @badLanguage     = &get_array("$FullPath/$BadLanguagePath"); 
  @data            = &get_array("$RATNGS"); 
  @rating_comments = &get_array("$CMTFLE") if (-e $CMTFLE);            
  
 ($total_votes, %FDATA) = &format_votes(@data, $voting_scale);

  $cookieExpireTime = $FORM{'exp'} if($defaultExpireTimeOnly =~ /no/i and $FORM{'exp'}); 
    
  if (!$FORM{'display'}) {
  
      if ($rating_comments[0] eq "") {
    
          %COMMENTS = (comment => "Nincs hozzászólás!",
                       number  => 1,
                      ); 
                      
          $FDATA{"comments"} = &template("$FullPath/$ViewComentsPath", \%COMMENTS);
    
      } else {  
  
          if ($FORM{'next'}) {
              $m = $FORM{'next'};   
          }
            elsif ($FORM{'previous'}) {
                $m = $FORM{'previous'};
            }          
          
          while ($n++ < $howmany_comments) {                      
             
             $_ = &filter_language($rating_comments[$m++], @badLanguage);
             
             $_ =~ s/\n|\r//g;
         
             %COMMENTS = (comment => $_,
                          number  => $n,
                         );
                         
             $FDATA{"comments"} .= &template("$FullPath/$ViewComentsPath", \%COMMENTS);
             
             last if ($m-1 == $#rating_comments); 
                               
          }
          
          $n=0;          
      }
           
      
      if ($m == $howmany_comments and $m <= $#rating_comments and $howmany_comments) {
          
          $number = $howmany_comments; 
          $number = ($#rating_comments + 1) - $m if (($#rating_comments + 1) - $m < $number);
          
          $FDATA{'previous'} = "<< Előző" if ($fill_in_Next_Previous =~ /yes/i);
          
          $FDATA{'next'} = "<a href=\"$ENV{SCRIPT_NAME}?id=$FORM{id}&next=$m\">Következő $number >></a>";
      
      }     
      
         elsif ($FORM{'next'} and $m > $#rating_comments) {
            
             $m = $FORM{'next'} - $howmany_comments;
             
             $FDATA{'next'} = "Következő >>" if ($fill_in_Next_Previous =~ /yes/i);
             
             $FDATA{'previous'} = "<a href=\"$ENV{SCRIPT_NAME}?id=$FORM{id}&previous=$m\"><< Előző $howmany_comments</a>";
         
         }  
                   
            elsif ($FORM{'next'} or $FORM{'previous'} and $m <= $#rating_comments) {
                
                $number = $howmany_comments; 
                $number = ($#rating_comments + 1) - $m if (($#rating_comments + 1) - $m < $howmany_comments);
                
                $FDATA{'next'} = "<a href=\"$ENV{SCRIPT_NAME}?id=$FORM{id}&next=$m\">Következő $number >></a>";
                
                $m = $FORM{'next'}     - $howmany_comments if($FORM{'next'});
                $m = $FORM{'previous'} - $howmany_comments if ($FORM{'previous'});
                
                $FDATA{'previous'} = "<a href=\"$ENV{SCRIPT_NAME}?id=$FORM{id}&previous=$m\"><< Előző $howmany_comments</a>"; 
          
            }
      
      print "Content-type: text/html\n\n";
   
      print &template("$FullPath/$ViewRatingsPath", \%FDATA);
      
      print &footer;         
      
  }   
   

  if ($FORM{'display'} =~ /form/i) {
              
      if ($place_link_after_maxchars =~ /yes/i) {
              
          $view_ratings_link = "[<a href=\"$ENV{SCRIPT_NAME}?id=$FORM{id}\">";
          $closing_tag = "</a>]";
                  
      }
              
      $n=0;
              
      foreach(@rating_comments) {       
                 
         last if ($n == $FORM{'maxcomments'});  
         $n++;
                 
         $_ = &filter_language($_, @badLanguage);
           
         if ($_ =~ /\*{3}/) {
             $n -= 1;
             next;
         }
             
         if ($FORM{'maxchars'}) {
             $_ =~ s/(.{$FORM{'maxchars'}}).*/$1$view_ratings_link...$closing_tag/;
         }
           
         %COMMENTS = (comment => $_,
                      number  => $n,
                     );
         
         $FDATA{"comments"} .= &template("$FullPath/$FormCommentsPath", \%COMMENTS);                       
                                  
      }
       
      if (!$FDATA{"comments"}) {
          
          %COMMENTS = (comment => "Nincs hozzászólás!",
                       number  => 1,
                      );
                          
          $FDATA{"comments"} = &template("$FullPath/$FormCommentsPath", \%COMMENTS);          
                        
      }   
                 
      $DefaultForm = $FORM{'form'} if ($FORM{'form'});
      
      $html  = &template("$FullPath/$FormPath/$DefaultForm", \%FDATA);
    
      $html .= "\n";

      while ($html =~ /(.*)(\n)|(\r)/g) {
         $_ = $1;
         $_ =~ s{\\}{\\\\}g;
         $_ =~ s/\"/\\"/g;
         $_ =~ s/\'/\\'/g;      
         $text .= " \"$_\" +\n";
      }

      chop($text) while ($i++ < 3);

      print "Content-Type: application/x-javascript\n\n";
      print "document.write($text);\n";   
   
  } 
   
  if ($FORM{'display'} =~ /hidden/i) {
      
      $UNAPPROVEDCMTFLE = $CMTFLE; 
      
      $UNAPPROVEDCMTFLE = "$FullPath/$UnapprovedCommentsPath" if ($approve_comments =~ /yes/i);
     
      if ( ($FORM{'rating'} or $FORM{'feedback'}) and ! defined $Cookie{$FORM{id}} ) {
 
          &setCookie($FORM{'id'}, $cookieExpireTime); 
 
          @comment = $FORM{'feedback'};
          
          foreach(@comment) {
             $_ =~ s/^\s+//;
             $temp_comment .= $_;    
          } 

          
          
          if ($temp_comment and $temp_comment !~ /^comments/i and $FORM{'feedback'}) {       
              
              my @comments = &get_array("$UNAPPROVEDCMTFLE");
              
              open (EOF, ">$UNAPPROVEDCMTFLE") or die "can't open file $!";
                flock(0,2); 
                  
                  foreach (@comment) {
                      $_ =~ s/\s+/ /g;
                      if ($approve_comments =~ /yes/i) { 
                          
                          unshift(@comments, "$FORM{'id'}|$_|\n");
                           
                      } else { 
                          unshift(@comments, "$_\n");
                      }
                  }
                  
                  print EOF @comments;

                flock(0,8);
              close(EOF);
          }
          

          open (EOF, ">$RATNGS") or die "can't open file $!";
            flock(0,2);

               if ($voting_scale > $#data) {  
               
                   $n = $m = $#data + 1 if ($data[0]);
                   
                   while ($n++ < $voting_scale) {
                     
                      $data[$m] = $n . "=0\n";

                      $m++;
                   }
                   $m=0;
                   $n=0;
               }
               
                  elsif ($voting_scale < $#data) {
                      
                       pop(@data) while($n++ < $voting_scale);
                       $n=0;
                       
                  }
                  
                                              
               foreach(@data) {
                  $n++;
                  if ($FORM{'rating'} == $n and $_ =~ s/^($n=)(\d+)//) {
                      $count = $2;
                      print EOF "$n=" . ++$count . "\n";
                  } else {
                    print EOF "$_";
                  }
               }
               $n=0;
              
            flock(0,8);
          close(EOF);

      }  
   
      $returnURL = $ENV{'HTTP_REFERER'} if (!$returnURL);
      $returnURL = $FORM{'returnURL'}   if ($FORM{'returnURL'});         
      
      if(!$returnURL) {
         print "Content-type:text/html\n\n";
         print qqć
           <body onload="history.go(-1);return true;">
           <noscript>
           <p>&nbsp;</p><p>&nbsp;</p><p align="center"><b>Nincs engedélyezve a Java Script futtatás:</b>
           <i> Klikkeljen a böngészőjében a VISSZA nyílra!</i></p>
           </noscript>
         ć;
             
      } else {
          print "Location: $returnURL\n\n";   
      } 
      
  } 
  
  if ($FORM{'display'} !~ /form|hidden|/i) {
  
      
      print "Content-type: text/html\n\n";
      print "<center><h2><font color=red face=\"arial\">" .
            "An error Has occurred.</font></h3> " .
            "<a href=\"#\" onClick=\"history.go(-1);return true;\">" .
            "<< Go Back</a></font>" .
            "</center>";
      
  }

  
exit;





sub format_votes {

    
    my (@data)  = @_; 
    my $voting_scale = pop(@data);
    
    my @votes; 
    my $n;
    my $m;
    my $total_votes;
    
    while($n++ < $voting_scale) {
        $data[$m++] =~ /$n=(\d*)/;
        $total_votes += $1;
        push(@votes,$1);
    }
  
    $n=0;
    $m=0;

    my $percent;  
    my $temp;
    my %percents;
    
    while($n++ < $voting_scale) {

       $percent  = sprintf("%.2f",$votes[$m]/$total_votes) if ($total_votes > 0);
       $percent *= 100;

       if ($votes[$m] > 0 and $percent == 0) {
           $percents{$n} = "<1%";

       } else {

         $percents{$n}    = $percent . "%";
         $temp            = $n     if ($percent == 100);
         $percents{$temp} = ">99%" if ($temp and $votes[$n]);

       }

       $m++;
    }     
  
    $n=0;  
 
  
    my %FDATA = (
                 ratingID    => $FORM{'id'},
                 returnURL   => $FORM{'returnURL'},
                 totalVotes  => $total_votes,
                 scriptURL   => $ENV{'SCRIPT_NAME'},
                 form        => $FORM{'form'},
                 maxchars    => $FORM{'maxchars'},
                 maxcomments => $FORM{'maxcomments'},             
                );     
                
    
    while ($n++ < $voting_scale) {
      $FDATA{"percents$n"} = $percents{$n};
      $FDATA{"votes$n"}    = $votes[$n-1] > 0 ? $votes[$n-1] : 0;
    }
    
    return ($total_votes, %FDATA);    
  
}




sub filter_language {
    my $text = shift;
    my $sensored;
    foreach(@_) {
       chomp;
       $sensored = "*" x length($_);
       $text =~ s/\b($_)/$sensored/ig;
    }
    
    return $text;
}





sub check_file_ext {

    $file = pop;
    foreach (@_) {
       if ($file =~ /($_)$/) {
           exit;
       }
    }
}




sub template {

    my ($filename, $fillings) = @_;
    my $text;

    local $/;
    local *F;	
	
    open(F, "< $filename\0") || return;		
      $text = <F>;
    close(F);	
	
    $text =~ s{ %% ( .*? ) %% }
              { exists( $fillings->{$1} )
                      ? $fillings->{$1} 
                      : ""
              }gsex;

    return $text;
    
}



sub check_ids {
    
    my $id = shift;
    my $found;
    foreach(@_) {
       chomp;      
       if ($_ =~ /^($id)$/i) {       
          $found = "yes";
          last;
       }    
    }
    if (!$found) {      
        print "Content-type: text/html\n\n";
        print <<"        ERROR";
        
        <center><h2>
         <font face=arial color=red>
          An error has occurred: Rating ID ( $id ) does not exist.
         </font></h2>
         <a href="#" onClick="history.go(-1);return true;">
         << Go Back</a>
        </center>
          
        ERROR
        exit;
    }
    return 1;
}



sub footer {

    print <<"    HTML";
    
   <center>
   <table height="">
    <tr>
     <td valign=bottom align=center>
      <!--p align='center'-->
       <font size=1 face=arial color=''>
     
        <a target="top" href="http://www.szentesinfo.hu/mozaik">Szentesi Mozaik</a> szavazógépe

       </font>
      </p>
     </td>
    </tr>
   </table>
   </center>
  </body> 
 </html>   
    
    HTML

    return;
}

