#!/usr/bin/perl
#
require './jcode.pl';
require './cgi-lib.pl';
#
#  簡易アンケート version 1.0 
#/*- [主な機能] ------------------------------------------------------------*/
#
#    ・簡易投票システムです
#    ・新規の項目が追加できます
#    ・最大登録件数が設定できます
#    ・連続投稿禁止機能がついてます
#
#/*- [設置構成] ------------------------------------------------------------*/
#
# /cgi-bin/
#    |                          < >内はパーミッション
#    +-- vote.cgi      <755>    アンケート本体
#    +-- votedata.cgi  <666>    集計データファイル
#    +-- jcode.pl      <444>    日本語ライブラリ
#    +-- cgi-lib.pl    <444>    CGIライブラリ
#
#/*- [History] -------------------------------------------------------------*/
#/* 2001/08/30     Ver1.0として公開                                         */
#/*                                                                         */
#/*-------------------------------------------------------------------------*/
#/*-------------------------------------*/
#/* 基本設定                            */
#/*-------------------------------------*/
$title     = '簡易アンケート';          # アンケートタイトル
$hp_addr   = "http://www.debu.ne.jp/tetsu/";  # 自ホームページアドレス
$hp_name   = "みんなの西川口";          # 自ホームページ名
$vote_file = "./votedata.cgi";          # データを記録するファイル
$gif       = './bar.gif';               # 画像バー
$MAX       = 1000;                      # 最大記録保存数
$method    = 'post';                    # 標準:post 直接:get
$wck       = 1;                         # 簡易２重投稿防止処理 する=1 しない=0
$cookie    = 'VoteCookie';              # cookie名(上記利用の場合設定)
#/*-------------------------------------*/
#/* 画面冒頭に入れるメッセージ(HTML式)  */
#/*-------------------------------------*/
$vote_message = '
<h3>あなたのお勧めのお店は！？</h3>
';
#/*-------------------------------------*/
#/* 画面設定                            */
#/*-------------------------------------*/
 $BODYC = '<BODY BGCOLOR="#EEEEEE" TEXT="#000000" LINK="#229955" VLINK="#999933">';
#$BODYC = '<BODY BGCOLOR="#000000" TEXT="#FFFFFF" LINK="#229955" VLINK="#999933">';

#/*-------------------------------------------------------------------------*/
    $ENV{'TZ'}   = 'JST-9';
    $Time_Now    = time;
    ($sec,$min,$hour,$mday,$month,$year,$youbi) = localtime($Time_Now);
    $year += 1900;
    $month++;
    $month      = "0$month"  if ($month < 10);
    $mday       = "0$mday"   if ($mday  < 10);
    $hour       = "0$hour"   if ($hour  < 10);
    $min        = "0$min"    if ($min   < 10);
    $sec        = "0$sec"    if ($sec   < 10);
    $date_now   = "$year年$month月$mday日 $hour時$min分$sec秒";
#/*-------------------------------------------------------------------------*/
sub ReadData {
    open(DB,"$vote_file") || ended('Error', '$vote_file open error');
        seek(DB,0,0);
        @lines = <DB>;
    close(DB);
}
#/*-------------------------------------------------------------------------*/
sub vote_main {
    
    ReadData();
    
    $iSousu = @lines;
    
    #集計最初のデータの投票時刻
    ($iDate, $iData) = split(/\t/,$lines[$iSousu - 1]);
    if ( $iDate eq '' ) { $first_date = $date_now; }
    else                { $first_date = $iDate;    }
    
    #集計最後のデータの投票時刻
    ($iDate, $iData) = split(/\t/,$lines[0]);
    if ( $iDate eq '' ) { $last_date = $first_date; }
    else                { $last_date = $iDate;      }
    
    #データ集計(空白を除外)
    foreach $line (@lines) {
        
        ($iDate, $iData) = split(/\t/,$line);
        if ($iData ne ' ' && $iData ne '') { push(@mShuu, $iData); }
    }
    
    #データ集計(個別＆総数カウント)
    $i = 0;
    foreach (@mShuu) { $ans{($_)[0]}++; $i++; }
    
    # 画面表示
    print qq(Content-type: text/html\n\n);
    
    print <<"EOF";
    <html>
    <head>
        <title>$title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=x-sjis">
        <META name="robots" content="noindex,nofollow">
    </head>
    $BODYC
    <CENTER>
    <H1>$title</H1>
    <DIV>$vote_message</DIV>
    </CENTER>
    <TABLE WIDTH=100%>
    <TR><TD>（<A HREF="$hp_addr">$hp_name</A>）</TD>
    <TD><FONT SIZE=2>
        <DIV ALIGN=RIGHT><B>$date_now</B></DIV>
        <DIV ALIGN=RIGHT>現在のアンケート集計結果</DIV>
        </FONT>
    </TD></TR>
    </TABLE>
    <hr noshade size=1>
    <FONT SIZE=2>
    <DIV>全投票数：<i><b>$iSousu</b></i></DIV>
    <DIV>有効回答数(白票以外)：<i><b>$i</b></i></DIV>
    </FONT>
    <table border=3 cellpadding=0 sellspacing=3>
EOF

    if ($bTou ne "1") {
        
        print "<tr><th>項目</th><th>投票数</th><th>投票</th>";
        print "<th>割合(%)</th><th>グラフ<br></th></tr>\n";
    }
    else {
        
        print "<tr><th>項目</th><th>投票数</th>";
        print "<th>割合(%)</th><th>グラフ<br></th></tr>\n";
    }

    foreach (sort { $ans{$b} <=> $ans{$a} } keys %ans) {

        $fPercent_ans = 100 * ($ans{$_} / $i);
        $fPercent_ans = sprintf("%2.1f",$fPercent_ans);

        $img = int($fPercent_ans) * 5;

        if ($bTou ne "1") {
            
            print <<"EOF";
            <form method="$method" action="$eScriptPath">
            <input type=hidden name="write" value="write">
            <input type=hidden name="vote" value="$_">
            <TR>
            <TD>$_</TD>
            <TD ALIGN=RIGHT>$ans{$_}</TD>
            <TD><input type=submit value="投票"></TD>
            <TD ALIGN=RIGHT>$fPercent_ans\%</TD>
            <TD nowrap><img src="$gif" WIDTH=$img HEIGHT=20></TD>
            </TR>
            </form>
EOF
        }
        else {

            print <<"EOF";
            <TR>
            <TD>$_</TD>
            <TD ALIGN=RIGHT>$ans{$_}</TD>
            <TD ALIGN=RIGHT>$fPercent_ans\%</TD>
            <TD nowrap><img src="$gif" WIDTH=$img HEIGHT=20></TD>
            </TR>
EOF
        }
    }
    
    if ($bTou ne "1") {
        print <<"EOF";
        <TR><TD COLSPAN=5>　</TD></TR>
        <form method="$method" action="$eScriptPath">
        <input type=hidden name="write" value="write">
        <TR>
            <TD COLSPAN=2><input type=text name="new" size=20></TD>
            <TD COLSPAN=3>
            <input type=submit value="新項目作成">　(該当無しの場合)</TD>
        </TR>
        </form>
EOF
    }

    print <<"EOF";
    </table>
    <TABLE WIDTH=100%>
    <TR><TD>
        <FONT SIZE=2>
        <DIV>集計開始：$first_date</DIV>
        <DIV>最終投票：$last_date</DIV>
        </FONT>
    </TD>
    <TD><FONT SIZE=2>
        <DIV ALIGN=RIGHT>最大アンケート集計件数： $MAX 件分</DIV>
        <DIV ALIGN=RIGHT>（これを超えると最新の$MAX件分の集計になります）</DIV>
        </FONT>
    </TD></TR>
    </TABLE>
    <HR>
EOF

}
#/*-------------------------------------------------------------------------*/
sub vote_w {
    
    if ($wck) { wcheck(); }
    
    if    ($iVote  ne "" && $iNVote ne "") { $write = "";      }
    elsif ($iVote  ne "")                  { $write = $iVote;  }
    elsif ($iNVote ne "")                  { $write = $iNVote; }
    
    ReadData();
    
    $Values = "$date_now\t$write\t$Time_Now\t$eHost\t\n";
    
    (@lines < $MAX-1) || (@lines = @lines[0 .. $MAX - 2]);
    unshift( @lines, $Values );
    open(DB,">$vote_file") || ended('Error', '$vote_file write error');
#       eval 'flock(DB,2);';
        seek(DB,0,0);
        print DB @lines;
#       eval 'flock(DB,8);';
    close(DB);
}
#/*-------------------------------------------------------------------------*/
sub wcheck {

    #(簡易)複数回投稿防止処理

    @pairs = split(/;/,$ENV{'HTTP_COOKIE'});
    foreach $pair (@pairs) {

        ($name, $value) = split(/=/, $pair);
        $name =~ s/ //g;
        $COOKIE{$name} = $value;
    }

    if ($COOKIE{$cookie} eq 'repost_check') { ended('複数投票できません','あなたは既に投票されました.'); }
    print "Set-Cookie: $cookie=repost_check;\n";
}

#/*-------------------------------------*/
#/* ＣＧＩ終了処理（エラー処理含む）    */
#/*-------------------------------------*/
sub ended
{
    local (@msg) = @_;
    local ($i);
    
    print qq(Content-type: text/html\n\n);
    
    print <<"EOF";
    <HTML>
    <HEAD>
        <TITLE>$title</TITLE>
        <meta http-equiv="Content-Type" content="text/html; charset=x-sjis">
        <META name="robots" content="noindex,nofollow">
        <META HTTP-EQUIV="Refresh" CONTENT="30;URL=$hp_addr">
    </HEAD>
    $BODYC
    <h1>$_[0]</h1>
EOF
    
    print qq(<ul>\n);
    foreach $i (1 .. $#msg) { print qq(<li>$msg[$i]\n); }
    
    print <<"EOF";
    <p>
    <li>【<a href="$hp_addr" target="_top">$hp_name</a>】
    <li>【<A HREF="JavaScript:history.back()">直前の画面</A>】
    </ul>
EOF

    copylight();
    exit;
}
#/*-------------------------------------*/
#/* ココは消したらダメ。絶対ダメ。      */
#/* ダメったらダメ                      */
#/*-------------------------------------*/
sub copylight
{
    print <<"EOF";
    <FONT SIZE=1>
    <div align=right><a href="http://www.groupies.jp/" target="_blank">
    ＧroupiesＪapan</a></div>
    </FONT>
    </body>
    </html>
EOF
}
    #/*---------------------------------*/
    #/*  main処理                       */
    #/*---------------------------------*/
    ReadParse();
    $eScriptPath = $ENV{'SCRIPT_NAME'};
    $eHost       = $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'};
    
    $iVote  = $in{'vote'};
    $iNVote = $in{'new'};
    $iWrite = $in{'write'};
    
    if    ($iWrite eq 'write') { $bTou = "1"; vote_w(); }
    vote_main();
    copylight();

exit;
