#!/usr/bin/perl

use DBI;

require "/usr/local/apache/cgi-bin/games2000/location.set";


###### getting form data

%formdata=();
%filenames=();

if( $ENV{'CONTENT_TYPE'}=~/multipart/ )
{
    binmode STDIN;
    read(STDIN, $query, $ENV{'CONTENT_LENGTH'});

    $query=~/\A(.+?)(\015|\012)/;
    $boundary = $1;

    (@allkeys) = split/$boundary/,$query;

    foreach $mykey (@allkeys) {

        if($mykey=~/name="(.+?)"/) {
            $keyname=$1;
            $mykey=~s/\A(.+?)\015{0,1}\012\015{0,1}\012//s;
            $keyinfo=$1;

            if( $keyinfo=~/filename="(.+?)"/ ) {
                $filename = $1;
            } else { $filename=""; }

            $mykey=~s/\015{0,1}\012\Z//;

            $formdata{$keyname}=$mykey;
            $filenames{$keyname}=$filename;
        }
    }
} else {
if( $ENV{'REQUEST_METHOD'} eq 'POST' )
{
    read(STDIN, $query, $ENV{'CONTENT_LENGTH'});

    @params=split(/&/, $query);
    foreach $keyvalueparam (@params) {
        ($keyparam, $valueparam) = split(/=/, $keyvalueparam);
        $valueparam=~tr/+/ /;
        $valueparam=~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $formdata{$keyparam}=$valueparam;
    }
} else
{
    $query = $ENV{'QUERY_STRING'};

    @params=split(/&/, $query);
    foreach $keyvalueparam (@params) {
        ($keyparam, $valueparam) = split(/=/, $keyvalueparam);
        $valueparam=~tr/+/ /;
        $valueparam=~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $formdata{$keyparam}=$valueparam;
    }
}
}

######  analyzing parameters

    
    $action = $formdata{'action'};
    $recordid = $formdata{selector};
    if( $recordid eq "") { $recordid = $formdata{recordid}; }

    $jsstart = "<script language='javascript'><!--\n";
    $jsend = "\n//--></script>";

    if( ($action eq "") or ($action eq "main") ) { show_main(); exit;}
    if( $action eq "insert" ) { insert_me(); exit;}

    if( $action eq "update" ) { update_me(); exit;}
    if( $action eq "delete" ) { delete_me(); exit;}

    if( $action eq "maketop" ) { maketop_me(); exit;}
    if( $action eq "makecurrent" ) { makecurrent_me(); exit;}
    if( $action eq "publish" ) { publish_me(); exit;}



    print $standardheader;
    print "Query error. Tell jager.";
    exit;


sub parse_client_cookies
{
    local (*COOKIE_DATA) = @_;
        
    local (@key_value_pairs, $key_value, $key, $value);
    @key_value_pairs = split (/;\s/, $ENV{'HTTP_COOKIE'});
    foreach $key_value (@key_value_pairs) {
        ($key, $value) = split (/=/, $key_value);
        $key   =~ tr/+/ /;
        $value =~ tr/+/ /;
        $key   =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        if (defined($FORM_DATA{$key})) {
            $FORM_DATA{$key} = join ("\0", $FORM_DATA{$key}, $value);
        } else {
	    $FORM_DATA{$key} = $value;
	}
    }
}
													    
													    








sub show_main() {
    print $standardheader;

    local $/=undef;
    open(T,"$tplpath/newshour_menu.html") || die "Cannot open template: $tplpath/newshour_menu.html";
    $template=<T>; close(T);

    open(T,"$tplpath/navigation") || die "Cannot open template: $tplpath/navigation";
    $navigation=<T>; close(T);
    ($navigationselected) = $navigation=~/::selected(.+?)selected::/s; $navigation=~s/::newshour::/$navigationselected/; $navigation=~s/::(.+?):://g;
    $template=~s/::navigation::/$navigation/;

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    ($jsblock) = $template=~/::jsblock(.+?)jsblock::/s;
    $jsfiller="";
    

    $sth = $dbh->prepare("select * from newshour order by newshour_sorter desc");
    $sth->execute;

    if($recordid ne "") { $selected=$recordid; } else {$selected=-1;};
    $newsblock="";
    for( $i=0; $i<$sth->rows; $i++) {
	$row = $sth->fetchrow_hashref;
	
	($myyear, $mymonth, $myday, $myhour, $myminute) = split/\D/, $row->{newshour_time};
        if( ($selected==$row->{newshour_id}) or (($selected==-1) and ($i==0))) { $isselected=" selected "; } else { $isselected="" };
        if( $row->{newshour_current} eq 1) { $isselected.=" style='background-color: black; color: white' "; } 


	$newsblock.="<option value=$row->{newshour_id}$isselected>$myday/$mymonth $myhour:$myminute $row->{newshour_name}</option>\n";

	$row->{newshour_text}=~s/\015//g;
	$row->{newshour_text}=~s/\\/\\\\/g;
	$row->{newshour_text}=~s/"/\\"/g;	
	$row->{newshour_text}=~s/\012/\\n/g;

	$row->{newshour_name}=~s/\\/\\\\/g;
	$row->{newshour_name}=~s/"/\\"/g;	
	$row->{newshour_name}=~s/\012/\\n/g;

	
	$jsblockcopy=$jsblock;
	$jsblockcopy=~s/::jsname::/$row->{newshour_name}/;
	$jsblockcopy=~s/::jstext::/$row->{newshour_text}/;
	$jsblockcopy=~s/::jspicture::/$row->{newshour_picture}/;
	$jsblockcopy=~s/::jstime::/$myday\/$mymonth\/$myyear $myhour:$myminute/;
	$jsblockcopy=~s/::jssource::/$row->{newshour_source}/;

	$jsblockcopy=~s/::jsid::/$row->{newshour_id}/;
	$jsfiller.=$jsblockcopy;	


    }
    $sth->finish;

    $template=~s/::scriptname::/$cgipath\/edit_newshour.pl/g;
    $template=~s/::newsblock::/$newsblock/;
    $template=~s/::jsblock(.+?)jsblock::/$jsfiller/s;
    
    print $template;

    $dbh->disconnect;
}



sub insert_me() {
    print $standardheader;

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sth = $dbh->prepare("insert into newshour (newshour_name, newshour_time, newshour_sorter) values (?, current_timestamp(), unix_timestamp())");
    $sth->execute($formdata{myinsert});
    $sth->finish;
    
    $sth = $dbh->prepare("select last_insert_id()");
    $sth->execute;
    $lastinsertid = $sth->fetchrow_arrayref->[0];
    $sth->finish;

    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main&recordid=$lastinsertid/;
    print $magicteleport;

    $dbh->disconnect;
}



sub update_me() {
    print $standardheader;


    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sth = $dbh->prepare("update newshour set newshour_name=?, newshour_text=?, newshour_time=?, newshour_source=?, newshour_picture=? where newshour_id=?");
    ($myday, $mymonth, $myyear, $myhour, $myminute) = split/\D/, $formdata{mytime};
    $sth->execute($formdata{mysubject}, $formdata{mytext}, "$myyear-$mymonth-$myday $myhour:$myminute:00", $formdata{mysource}, $formdata{mypicturename}, $recordid);
    $sth->finish;


    if( $filenames{mypicturefile} ne "" ) {  ### incoming foto
	($extension) = ($filenames{mypicturefile}=~/.+\.(.+)/);
    
	open( MYIMAGEFILE, ">$htmldir/images/newshour/$recordid\.$extension");
	binmode MYIMAGEFILE;
	print MYIMAGEFILE $formdata{mypicturefile};
	close MYIMAGEFILE;
	
	chmod 0664, "$htmldir/images/newshour/$recordid\.$extension";
	
	$sth = $dbh->prepare("update newshour set newshour_picture=? where newshour_id=?");
	$sth->execute("/games2000/images/newshour/$recordid\.$extension", $recordid);
	$sth->finish;
    }
    
    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $dbh->disconnect;
}


sub delete_me() {
    print $standardheader;

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sth = $dbh->prepare("delete from newshour where newshour_id=?");
    $sth->execute($recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main/;
    print $magicteleport;

    $dbh->disconnect;
}



sub maketop_me() {
    print $standardheader;

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sth = $dbh->prepare("update newshour set newshour_sorter=unix_timestamp() where newshour_id=?");
    $sth->execute($recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $dbh->disconnect;
}


sub makecurrent_me() {
    print $standardheader;

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sth = $dbh->prepare("update newshour set newshour_current=0");
    $sth->execute;
    $sth->finish;

    $sth = $dbh->prepare("update newshour set newshour_current=1 where newshour_id=?");
    $sth->execute($recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $dbh->disconnect;
}




sub publish_me() {
    print $standardheader;

    local $/=undef;
    open(T,"$tplpath/newshour_lenta.html") || die "Cannot 1open template: $tplpath/newshour_lenta.html";
    $template=<T>; close(T);

    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
    if( !$dbh ) {
        print "Unable to open database\n";
        exit;
    }

    $sthsend = $dbh->prepare("insert into upload_demon (upload_frompath, upload_topath, upload_server, upload_login, upload_password) values (?,?,?,?,?)");

    ($lentablock) = $template=~/::lentablock(.+?)lentablock::/s;
    $lentafiller="";

    $sth = $dbh->prepare("select * from newshour order by newshour_sorter desc");
    $sth->execute();
    
    for($i=0; $i < $sth->rows; $i++) {
    
	$row = $sth->fetchrow_hashref;
	
	$lentablockcopy = $lentablock;
	
	$row->{newshour_name}=~s/</&lt;/g;
	$row->{newshour_text}=~s/</&lt;/g;
	$row->{newshour_text}=~s/\015//g;
	$row->{newshour_text}=~s/\012/<br>/g;
	$row->{newshour_text}=~s/  /&nbsp; /g;

	$lentablockcopy =~s/::lentatext::/$row->{newshour_text}/;
	$lentablockcopy =~s/::lentaheader::/$row->{newshour_name}/;    
	($myyear, $mymonth, $myday, $myhour, $myminute) = split/\D/, $row->{newshour_time};
	$lentablockcopy =~s/::lentatime::/$myhour:$myminute/;
	$lentablockcopy =~s/::lentasource::/$row->{newshour_source}/;

	if( $row->{newshour_picture} eq "" ) {
	    $lentablockcopy=~s/::lentapictureblock(.+?)lentapictureblock:://s;
	} else {
	    $lentablockcopy=~s/(::)*lentapictureblock(::)*//g;
	    $lentablockcopy=~s/::lentapicture::/$row->{newshour_picture}/;

	    $sthsend->execute("/usr/local/apache/htdocs$row->{newshour_picture}", "/bhome/part2/01/vh01002/www/images", "195.2.64.17", "vh01002", "9AJKZVqT");
	}
    	
	$lentafiller.=$lentablockcopy;
    }
    $sth->finish;
    
    $template=~s/::lentablock(.+?)lentablock::/$lentafiller/s;
    
    open(MYCLOWN, ">$htmldir/newshour_lenta.shtml");
    print MYCLOWN $template;
    close(MYCLOWN);
        
    chmod 0666, "$htmldir/newshour_lenta.shtml";
    $sthsend->execute("$htmldir/newshour_lenta.shtml", "/bhome/part2/01/vh01002/www/games2000", "195.2.64.17", "vh01002", "9AJKZVqT");


# Отжимаем новость часа

    local $/=undef;
    open(T,"$tplpath/games2000_newshour.html") || die "Cannot open template: $tplpath/games2000_newshour.html";
    $template=<T>; close(T);


    $sth = $dbh->prepare("select * from newshour where newshour_current=1");
    $sth->execute();
    
    $row = $sth->fetchrow_hashref;
    $row->{newshour_name}=~s/</&lt;/g;
    $row->{newshour_text}=~s/</&lt;/g;
    $row->{newshour_text}=~s/\015//g;
    $row->{newshour_text}=~s/\012/<br>/g;
    $row->{newshour_text}=~s/  /&nbsp; /g;


    $template =~s/::newshourtext::/$row->{newshour_text}/;
    $template =~s/::newshourheader::/$row->{newshour_name}/;    
    ($myyear, $mymonth, $myday, $myhour, $myminute) = split/\D/, $row->{newshour_time};
    $template =~s/::lentatime::/$myhour:$myminute/;
    $template =~s/::newshoursource::/$row->{newshour_source}/;

    if( $row->{newshour_picture} eq "" ) {
        $template=~s/::newshourphoto::/\/images\/trance.gif/s;
    } else {
        $template=~s/::newshourphoto::/$row->{newshour_picture}/;
        $sthsend->execute("/usr/local/apache/htdocs$row->{newshour_picture}", "/bhome/part2/01/vh01002/www/games2000/images/newshour", "195.2.64.17", "vh01002", "9AJKZVqT");
    }
    $sth->finish;
    
    open(MYCLOWN, ">$htmldir/includes/games2000_newshour.ssi");
    print MYCLOWN $template;
    close(MYCLOWN);
        
    chmod 0666, "$htmldir/includes/games2000_newshour.ssi";
    $sthsend->execute("$htmldir/includes/games2000_newshour.ssi", "/bhome/part2/01/vh01002/www/games2000/includes", "195.2.64.17", "vh01002", "9AJKZVqT");


    $magicteleport =~s/::whereto::/edit_newshour.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $sthsend->finish;
    $dbh->disconnect;
}


