#!/usr/bin/perl

use DBI;

if( $^O=~/linux/ ) {
    require "/usr/local/apache/cgi-bin/games2000/location.set";
} else {
    require "/opt/clients/gazeta/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 "makenewshour" ) { makenewshour_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/news_menu.html") || die "Cannot open template: $tplpath/news_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/::news::/$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 news order by new_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->{new_time};
        if( ($selected==$row->{new_id}) or (($selected==-1) and ($i==0))) { $isselected=" selected "; } else { $isselected="" };

        if( $row->{new_ugansk} eq 1) { $isselected.=" style='background-color: #E0E0E0;' "; } 

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

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

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

	
	$jsblockcopy=$jsblock;
	$jsblockcopy=~s/::jsname::/$row->{new_name}/;
	$jsblockcopy=~s/::jstext::/$row->{new_text}/;
	$jsblockcopy=~s/::jstime::/$myday\/$mymonth\/$myyear $myhour:$myminute/;
	$jsblockcopy=~s/::jssource::/$row->{new_source}/;

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


    }
    $sth->finish;

    $template=~s/::scriptname::/$cgipath\/edit_news.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 news (new_name, new_time, new_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_news.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 news set new_name=?, new_text=?, new_time=?, new_source=?, new_ugansk=? where new_id=?");
    ($myday, $mymonth, $myyear, $myhour, $myminute) = split/\D/, $formdata{mytime};
    $sth->execute($formdata{mysubject}, $formdata{mytext}, "$myyear-$mymonth-$myday $myhour:$myminute:00", $formdata{mysource}, ($localcopy eq 'yeah'?0:1), $recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_news.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 news where new_id=?");
    $sth->execute($recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_news.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 news set new_sorter=unix_timestamp() where new_id=?");
    $sth->execute($recordid);
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_news.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $dbh->disconnect;
}




sub publish_me() {
    print $standardheader;

    local $/=undef;
    open(T,"$tplpath/news_lenta.html") || die "Cannot 1open template: $tplpath/news_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 news order by new_sorter desc");
    $sth->execute();
    
    for($i=0; $i < $sth->rows; $i++) {
    
	$row = $sth->fetchrow_hashref;
	
	$lentablockcopy = $lentablock;
	
	$row->{new_name}=~s/</&lt;/g;
	$row->{new_text}=~s/</&lt;/g;
	$row->{new_text}=~s/\015//g;
	$row->{new_text}=~s/\012/<br>/g;

	$lentablockcopy =~s/::lentatext::/$row->{new_text}/;
	$lentablockcopy =~s/::lentaheader::/$row->{new_name}/;    
	($myyear, $mymonth, $myday, $myhour, $myminute) = split/\D/, $row->{new_time};
	$lentablockcopy =~s/::lentatime::/$myhour:$myminute/;
	$lentablockcopy =~s/::lentasource::/$row->{new_source}/;
	$lentablockcopy=~s/::lentapictureblock(.+?)lentapictureblock:://s;
    	
	$lentafiller.=$lentablockcopy;
    }
    $sth->finish;
    
    $template=~s/::lentablock(.+?)lentablock::/$lentafiller/s;
    
    open(MYCLOWN, ">$htmldir/news_lenta.shtml");
    print MYCLOWN $template;
    close(MYCLOWN);
        
    chmod 0666, "$htmldir/news_lenta.shtml";
#    $sthsend->execute("$htmldir/news_lenta.shtml", "/home/jager/horde", "mail.gazeta.ru", "jager", "v4rkal0s");
    $sthsend->execute("$htmldir/news_lenta.shtml", "/bhome/part2/01/vh01002/www/games2000", "195.2.64.17", "vh01002", "9AJKZVqT");
    
    
    $magicteleport =~s/::whereto::/edit_news.pl?action=main&recordid=$recordid/;
    print $magicteleport;

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


sub makenewshour_me() {
    print $standardheader;

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

    $sth = $dbh->prepare("select * from news where new_id=?");
    $sth->execute($recordid);
    $row = $sth->fetchrow_hashref;
    
    $sthins = $dbh->prepare("insert into newshour (newshour_name, newshour_time, newshour_sorter, newshour_text, newshour_source) values (?, ?, unix_timestamp(),?,?)");
    $sthins->execute($row->{new_name}, $row->{new_time}, $row->{new_text}, $row->{new_source});

    $sthins->finish;
    $sth->finish;
    
    $magicteleport =~s/::whereto::/edit_news.pl?action=main&recordid=$recordid/;
    print $magicteleport;

    $dbh->disconnect;
}
