#!/usr/bin/perl -w
# vim: set sw=4 ts=4 si et: 
#
# Copyright: GPL
# Author: Guido Socher
#
# Usage lfpoll 'voteid=01&lang=1'
#       lfpoll 'sel=before+2005&voteid=01&lang=1'
use strict;
#global data:
#
# version:
my $ver = "0.7";
my %FORM;
my $remadr; # REMOTE_ADDR avoid repeted votes form same host
#             The person can vote again after someone from an other
#             domain did already vote.
#
# If you add a new language the do not forget to also add a
# __ voteresulthead_X __ template at the end of the program
# languages: 1 = en, 2=de, 3=fr, 4=nl
#
#--------------on bearix:
# The address of this program (http address):
my $url = "http://bearix/cgi-bin/lfpoll";
# The address of the directory with the images:
my $img="http://bearix/homepages/guido/lfnew/common/images";
# the directory where the poll data files are stored (must be a chmod 1777 directory):
my $dbdir="/home/guido/lfdata/poll";
#--------------
#
#
print "Content-type: text/html\n\n";
#
&cgi_receive;
if ($FORM{'voteid'}){
    &vote;
}else{
    &printHTMLpage('greet');
}
#--------------------------------------------------------
sub printHTMLpage($){
    my $reqpage = shift;
    #read and print any text between __ $reqpage __ and the next __ 
    my $prt = 0;
    while(<DATA>){
        next unless ($prt || /^__ $reqpage __/o);
        if (/^__ $reqpage __/o){
            $prt = 1;
            next;
        }
        last if (/^__ /);
        s/\$url/$url/o;
        print;
    }
    print "<p>ERROR: page template missing for __ $reqpage __</p>\n" unless($prt);
}
#--------------------------------------------------------
sub vote{
    my ($total,$i,$dbstr,$abs,$percent,$ind);
    my @dat;
    my $file;
    my @line;
    $ENV{'PATH'} = "/bin:/usr/bin";
    unless($FORM{'voteid'}){
        &printHTMLpage('errorvoteid');
        return(0);
    }
    $FORM{'lang'}="1" unless ($FORM{'lang'});
    $FORM{'lang'}="20" if ($FORM{'lang'}>20);
    if ($FORM{'sel'}){
        #the user did vote:
        #
        # check for repeated votes:
        #
        $file="$dbdir/".$FORM{'voteid'}."_lasthost.txt";
        if ((-r "$file") && ((-M "$file")< 0.01)){
            # file was modified within the last 15 minutes
            # check who voted:
            if (open(DBI,"$file")){
                while(<DBI>){
                    chomp;
                    if ($_ eq $remadr){
                        &printHTMLpage('repeated');
                        close DBI;
                        return(0);
                    }
                }
                close DBI;
            }
        }
        unless (open(DBI,">$dbdir/".$FORM{'voteid'}."_lasthost.txt")){
            &printHTMLpage('writenovotedb');
            return(0);
        } 
        print DBI "$remadr\n";
        close DBI;
        #---------------------
        unless (open(DB,"$dbdir/".$FORM{'voteid'}.".txt")){
            &printHTMLpage('novotedb');
            return(0);
        } 
        @dat=<DB>;
        close DB;

        $total=0;$i=0;
        for (@dat){
            chomp;
            next unless(/^\d/);
            @line=split(/~/);
            unless($line[$FORM{'lang'}]){
                &printHTMLpage('nosuchlanguage');
                return(0);
            }
            $line[0]=~s/\D//g;
            # handle 1~~~something~ to not generate undef
            for $ind (1 .. $FORM{'lang'}){
                $line[$ind]="" unless($line[$ind]);
            }
            # you can use english values for other languages:
            if (index($_,$FORM{'sel'}) > 0){
                $line[0]++;
                $i++;
                $_=join("~",@line);
            }
            $total+=$line[0];
        }
        if ($total<1){
            &printHTMLpage('novotsyet');
            return(0);
        } 
        unless ($i){
            &printHTMLpage('novotekey');
            return(0);
        } 
        $dbstr=join("\n",@dat);
        unless (open(DB,">$dbdir/".$FORM{'voteid'}.".txt")){
            &printHTMLpage('writenovotedb');
            return(0);
        } 
        # this is probably almost atomic:
        print DB $dbstr;
        close DB;
        #
    }else{
        #view results only:
        unless (open(DB,"$dbdir/".$FORM{'voteid'}.".txt")){
            &printHTMLpage('novotedb');
            return(0);
        } 
        @dat=<DB>;
        close DB;
        $total=0;
        for (@dat){
            next unless(/^\d/);
            @line=split(/~/);
            $line[0]=~s/\D//g;
            $total+=$line[0];
        }
        if ($total<1){
            &printHTMLpage('novotsyet');
            return(0);
        } 
    }
    # data now evaluate:
    #
    &printHTMLpage('voteresulthead_'.$FORM{'lang'});
    for (@dat){
        chomp;
        next unless(/^\d/);
        @line=split(/~/);
        $line[$FORM{'lang'}]="invalid language" unless($line[$FORM{'lang'}]);
        $abs=$line[0];
        $percent=int($abs * 100 / $total);
        print " <tr><td>$line[$FORM{lang}]</td><td><img height=9 src=\"$img/vote_left.gif\"><img height=9 width=\"$percent\" src=\"$img/vote_middle.gif\"><img height=9 src=\"$img/vote_right.gif\"> $percent % </td><td>$abs</td></tr>\n";
    }
    print "</TABLE><br>\n";
    print "</TABLE><br>\n";
    print "<hr WIDTH=\"85%\" noshade size=\"1\"><center><font size=\"2\">generated by lfpoll version $ver</font><hr WIDTH=\"85%\" noshade size=\"1\"></center>\n";
    print "
 <SCRIPT LANGUAGE=\"JavaScript\">
 <!--  to hide script contents from old browsers
 bbutton();
 //-->
 </SCRIPT>\n\n";
}
#--------------------------------------------------------
#--------------------------------------------------------
sub cgi_receive{
    my $buffer = "";
    my $pair;
    my $name;
    my $value;
    if ($ENV{'GATEWAY_INTERFACE'} && $ENV{'GATEWAY_INTERFACE'} =~ /CGI/){
        if ($ENV{'REQUEST_METHOD'} eq 'GET') {
            if($ENV{'QUERY_STRING'}){
                $buffer = $ENV{'QUERY_STRING'};
            }
        }elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
            read(STDIN, $buffer,$ENV{'CONTENT_LENGTH'});
        }else{
            die "webfgrep Unknown REQUEST_METHOD: $ENV{'REQUEST_METHOD'}";
        }
    }else {
        $buffer = $ARGV[0] if ($ARGV[0]);
    }
    if ($ENV{'REMOTE_ADDR'}){
        $remadr=$ENV{'REMOTE_ADDR'};
    }else{
        $remadr='0.0.0.0';
    }
    # now decode it:
    #
    # Split the name-value pairs
    foreach $pair (split(/&/o, $buffer)){
        ($name, $value) = split(/=/, $pair);
        next unless ($value);
        # Un-Webify plus signs and %-encoding
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $FORM{$name} = $value;
    }
}

#--------------------------------------------------------
__END__

__ greet __
<HTML>
<HEAD>
   <TITLE>lfvote</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H2>Take this example and modify it</H2>

<p>Use a new vote ID for every new type of poll</p>
<h2>World domination</h2>
<TABLE CELLSPACING=1 CELLPADDING=1 BORDER=0>

<TR><TD>
 <TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0 BGCOLOR="#FFFFFF" width="30%">
 <TR><TD>
 <p>Question: When will Linux be the dominating operating system in the world?
 </p>
 </TD></TR>
 <TR><TD>
 <TR>
   <TD BGCOLOR="#BEBEBE">
    <FORM METHOD="get" ACTION="$url">
    <INPUT TYPE="radio" NAME="sel" VALUE="before 2005">before year 2005<BR>
    <INPUT TYPE="radio" NAME="sel" VALUE="around 2005" CHECKED>around year 2005<BR>
    <INPUT TYPE="radio" NAME="sel" VALUE="around 2010">around year 2010<BR>
    <INPUT TYPE="radio" NAME="sel" VALUE="never">never<BR>
    <INPUT TYPE="hidden" NAME="voteid" VALUE="01">
    <INPUT TYPE="hidden" NAME="lang" VALUE="1">
    <INPUT TYPE="submit" VALUE="vote!">
    </FORM>
    <br><div align="right"><font size="1"><a href="$url?voteid=01&lang=1">results</a></font></div>
   </TD>
 </TR>
 </TABLE>

</TD></TR>
</TABLE>
<!-- you must create a file (in $dbdir) with the name of voteid.txt (01.txt) and
put the following into it:
intiialvalue;value tag language 1;value tag language 2;value tag language 3;

In the above case this would be (languages english and german):
0~before 2005~vor 2005~
1~around 2005~um 2005~
0~around 2010~um 2010~
0~never~nie~

You must also create an empty file with the 
name voteid_lasthost.txt (01_lasthost.txt)
-->
</BODY>
</HTML>

__ voteresulthead_1 __
<HTML>
<!-- vote results for language 1 (english) -->
<HEAD>
<TITLE>lfvote results</TITLE>
<!-- people that have java script switched off do not see the button -->
<script language="JavaScript">
<!--  to hide script contents from old browsers
function bbutton(){
    document.open();
    document.writeln('<table border="0"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln(' <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('  <table border="3"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln('   <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('    <A href="javascript:history.back()"><b>&nbsp;Back&nbsp;</b></a>');
    document.writeln('   </td></tr></table>');
    document.writeln('</td></tr></table>');
    document.writeln('</center>');
}
//-->
</script>
</HEAD>
<BODY LINK="#1C1C1C">
<center>
<h2>LinuxFocus vote results</h2>
<TABLE CELLSPACING=2 CELLPADDING=1 BORDER=1>
<tr><th>What</th><th>Percentage</th><th>Absolute number of votes</th></tr>

__ voteresulthead_2 __
<HTML>
<!-- vote results for language 2 (german) -->
<HEAD>
<TITLE>lfvote Ergebnis</TITLE>
<!-- people that have java script switched off do not see the button -->
<script language="JavaScript">
<!--  to hide script contents from old browsers
function bbutton(){
    document.open();
    document.writeln('<table border="0"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln(' <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('  <table border="3"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln('   <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('    <A href="javascript:history.back()"><b>&nbsp;Zur&uuml;ck&nbsp;</b></a>');
    document.writeln('   </td></tr></table>');
    document.writeln('</td></tr></table>');
    document.writeln('</center>');
}
//-->
</script>
</HEAD>
<HTML>
<BODY LINK="#1C1C1C">
<center>
<h2>LinuxFocus Umfrageergebnisse</h2>
<TABLE CELLSPACING=2 CELLPADDING=1 BORDER=1>
<tr><th>Antwort</th><th>Prozent</th><th>Absolute Anzahl der Stimmen</th></tr>

__ voteresulthead_3 __
<HTML>
<!-- vote results for language 3 (french) -->
<HEAD>
<TITLE>lfvote R&egrave;sultats</TITLE>
<!-- people that have java script switched off do not see the button -->
<script language="JavaScript">
<!--  to hide script contents from old browsers
function bbutton(){
    document.open();
    document.writeln('<table border="0"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln(' <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('  <table border="3"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln('   <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('    <A href="javascript:history.back()"><b>&nbsp;Retour&nbsp;</b></a>');
    document.writeln('   </td></tr></table>');
    document.writeln('</td></tr></table>');
    document.writeln('</center>');
}
//-->
</script>
</HEAD>
<BODY LINK="#1C1C1C">
<center>
<h2>Rsultats de votes de LinuxFocus</h2>
<TABLE CELLSPACING=2 CELLPADDING=1 BORDER=1>
<tr><th>R&egrave;ponse</th><th>Pourcentage</th><th>Nombre total de votes</th></tr>

__ voteresulthead_4 __
<HTML>
<!-- vote results for language 4 (dutch) -->
<HEAD>
<TITLE>lfvote resultaten</TITLE>
<!-- people that have java script switched off do not see the button -->
<script language="JavaScript">
<!--  to hide script contents from old browsers
function bbutton(){
    document.open();
    document.writeln('<table border="0"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln(' <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('  <table border="3"  CELLSPACING="2" CELLPADDING="1">');
    document.writeln('   <tr BGCOLOR="#C2C2C2"><td align=center>');
    document.writeln('    <A href="javascript:history.back()"><b>&nbsp;Back&nbsp;</b></a>');
    document.writeln('   </td></tr></table>');
    document.writeln('</td></tr></table>');
    document.writeln('</center>');
}
//-->
</script>
</HEAD>
<BODY LINK="#1C1C1C">
<center>
<h2>LinuxFocus vote resultaten</h2>
<TABLE CELLSPACING=2 CELLPADDING=1 BORDER=1>
<tr><th>Wat</th><th>Percentage</th><th>Aantal stemmen</th></tr>

__ nosuchlanguage __
<HTML>
<BODY BGCOLOR="#EEEEEE">
<p>ERROR, the requested language is not defined in the vote database file.</p>
</BODY>
</HTML>

__ novotekey __
<HTML>
<BODY BGCOLOR="#EEEEEE">
<p>ERROR, Input value for the requested language not found in db-file.</p>
</BODY>
</HTML>


__ writenovotedb __
<HTML>
<BODY>
<p>ERROR, can not write to the vote database file.</p>
</BODY>
</HTML>


__ novotsyet __
<HTML>
<BODY>
<p>No voting data available.</p>
</BODY>
</HTML>

__ novotedb __
<HTML>
<BODY>
<p>ERROR, invalid vote database selected.</p>
</BODY>
</HTML>


__ repeated __
<HTML>
<HEAD>
<TITLE>lfvote error</TITLE>
</HEAD>
<BODY>
<p>Sorry, you may vote only once.</p>
</BODY>
</HTML>

__ errorvoteid __
<HTML>
<BODY>
<p>ERROR, I could not understand your request. Voteid missing</p>
</BODY>
</HTML>

__ ende __
