#!/usr/local/bin/perl -w
###############################################################################
# vote.pl - this code displays the pda vote page 
#
# Copyright (C) 2001 Norbert "Momo_102" Kuemin
# momo_102@bluemail.ch
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
###############################################################################
# pre stories cache update
use strict;
use lib '/home/slash';
use vars '%I';
use Slash;
use AvantGo;

my %LINKS;
my $comment = "";

##### Configuration #############################################
my $AVG = new AvantGo("/home/slash/avantgo.user");

#################################################################
sub main {
   *I = getSlashConf();
   getSlash();
   my $title = "$I{sitename} Umfrage";

   $AVG->env_load();    
   $AVG->user_load(); 
   my ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get("-");
   if ($AVG->env_get("USERID") ne "") { ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get(); }

   my ($qid) = sqlSelect( "qid", "pollquestions", "", "ORDER BY date DESC LIMIT 1");
   pda_header($title);
   pda_vote_nav($qid);
   print "<HR>\n";
   pda_vote_title($title);
   if (CGI::param("save")) { pda_vote_save($I{F}{qid}, $I{F}{aid}); }
   my $voters = pda_vote_question($qid);
   if (CGI::param("result") || CGI::param("save") || ($uid == -1 && ! $I{allow_anonymous})) {
      pda_vote_result($qid, $voters);
   } else {
      pda_vote_input($qid, $voters);
   }
   pda_vote_footer();
   print "<HR>\n";
   pda_vote_nav($qid);
   pda_footer();
}

#################################################################
sub pda_header {
   my $title = shift;
   print CGI::header();
   print <<EOT if $title;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML><HEAD><TITLE>$title</TITLE></HEAD><BODY>
EOT
}

#################################################################
sub pda_footer {
   print <<EOT;
</BODY></HTML>
EOT
}

#################################################################
sub pda_vote_title {
}

#################################################################
sub pda_vote_nav {
   my ($qid) = @_;
   my ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get("-");
   if ($AVG->env_get("USERID") ne "") { ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get(); }
   print "<A HREF=\"index.pl\">Home</A> ";
   if (CGI::param("result") || CGI::param("save")) {
      print "<A HREF=\"vote.pl\">Poll</A> ";
   } else {
      print "<A HREF=\"vote.pl?result=1\">Results</A> ";
   }
   if ($commenttype ne "none") {
      if ($comment eq "") {
         ($comment) = sqlSelect("count(*)", "comments", "sid='$qid'");
      }
      if ($comment > 0) {
         print "<A HREF=\"comment.pl?sid=$qid\">Comment($comment)</A> ";
      }
   }
   print "\n";
}

#################################################################
sub pda_vote_question {
   my ($qid) = @_;            
   my ($question, $voters) = sqlSelect( "question, voters", "pollquestions", "qid='$qid'");
   print "<B>".$question."</B>\n";
   print "<P>\n";
   return $voters;
}
 
#################################################################
sub pda_vote_result {
   my ($qid, $voters) = @_;
   my $c = sqlSelectMany("answer,votes", "pollanswers", "qid='$qid' ORDER by aid");
   while (my($answers, $votes) = $c->fetchrow) {
      my $p = int($votes / $voters * 100 + 0.5);
      print $answers.":<BR>";
      if ($p > 0) { print "<IMG SRC=\"vbar$p.gif\"> "; }
      print $p."% ($votes)<BR>\n";
   }
   $c->finish;
}
 
#################################################################
sub pda_vote_input {
   my ($qid, $voters) = @_;
   print "<FORM METHOD=\"POST\" ACTION=\"vote.pl?action=save\">\n";
   print "<INPUT TYPE=\"hidden\" NAME=\"save\" VALUE=\"1\">\n";
   print "<INPUT TYPE=\"hidden\" NAME=\"qid\" VALUE=\"$qid\">\n";
   my $c = sqlSelectMany("answer,aid", "pollanswers", "qid='$qid' ORDER by aid");
   while (my($answers, $aid) = $c->fetchrow) {
      print "<INPUT TYPE=\"radio\" NAME=\"aid\" VALUE=\"$aid\">$answers<BR>\n";
   }
   $c->finish;
   print "<INPUT TYPE=\"submit\" VALUE=\"Vote\">\n";
}

#################################################################
sub pda_vote_save {
   my ($qid, $aid) = @_;
   my $qid_dbi = $I{dbh}->quote($qid);

   my ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get("-");
   if ($AVG->env_get("USERID") ne "") { ($story, $commenttype, $poll, $hof, $uid) = $AVG->user_get(); }

   my($nickname) = sqlSelect("nickname","users", "uid=$uid");

   # get valid answer IDs
   my(%all_aid) = map { ($_->[0], 1) }
   @{sqlSelectAll("aid", "pollanswers", "qid=$qid_dbi")} if $qid;

   if (! keys %all_aid) {
      print "Ung&uuml;ltige Umfrage!<BR>";
      # Non-zero denotes error condition and that comments should not be 
      # printed.
      return;
   }

   my $qid_htm = stripByMode($qid, 'attribute');

   my $notes = "";
   if ($uid == -1 && ! $I{allow_anonymous}) {
      $notes = "Du kannst nicht anonym w&auml;hlen.  " .
        qq[also, <A HREF="sign.pl?action=on">log dich ein</A>.];
   } elsif ($aid > 0) {
      my $id = 0;
      if ($uid == -1) {
         ($id) = sqlSelect("id","pollvoters", "qid=$qid_dbi AND id=".
            $I{dbh}->quote($ENV{REMOTE_ADDR}.$ENV{HTTP_X_FORWARDED_FOR}).
            " AND uid=".$I{dbh}->quote($uid));
      } else {
         ($id) = sqlSelect("id","pollvoters", "qid=$qid_dbi AND uid=".$I{dbh}->quote($uid));
      }
      if ($id) {
         if ($uid == -1) {
            $notes = "$nickname auf $ENV{REMOTE_ADDR} hat schon gew&auml;hlt.";
         } else {
            $notes = "$nickname hat schon gew&auml;hlt.";
         }
         if ($ENV{HTTP_X_FORWARDED_FOR}) { 
            $notes .= " (proxy f&uuml;r $ENV{HTTP_X_FORWARDED_FOR})";
         }
      } elsif (exists $all_aid{$aid}) {
         $notes = "Deine Stimme ($aid) wurde registriert.";
         sqlInsert("pollvoters", {
            qid     => $qid, 
            id      => $ENV{REMOTE_ADDR}.$ENV{HTTP_X_FORWARDED_FOR},
            -'time' => 'now()',
            uid     => $uid
         });
         $I{dbh}->do("update pollquestions set voters=voters+1 where qid=$qid_dbi");
         $I{dbh}->do("update pollanswers set votes=votes+1 where qid=$qid_dbi and aid=".
            $I{dbh}->quote($aid));
      } else {
         $notes = "Deine Stimme ($aid) wurde abgewiesen.";
      }
   }
   print "<CENTER>$notes</CENTER><P>\n";
}

#################################################################
sub pda_vote_footer {
}

#################################################################
main();
#################################################################
