#!/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/maket_menu.html") || die "Cannot open template: $tplpath/maket_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/::maket::/$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 articles order by article_time 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->{article_time};
        if( ($selected==$row->{article_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->{article_id}$isselected>$row->{article_name}</option>\n";

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

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

	
	$jsblockcopy=$jsblock;
	$jsblockcopy=~s/::jsname::/$row->{article_name}/;
	$jsblockcopy=~s/::jstext::/$row->{article_text}/;
	$jsblockcopy=~s/::jspicture::/$row->{article_picture1}/;
        $jsblockcopy=~s/::jspictureuho::/$row->{article_picture2}/;
	$jsblockcopy=~s/::jstime::/$myday\/$mymonth\/$myyear $myhour:$myminute/;
#	$jsblockcopy=~s/::jssource::/$row->{newshour_source}/;


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




# ------- scan articles from PG

    local $/="\n";

    while( </usr/local/apache/cgi-bin/pg2/base/temp.*> ) {
    	
	($articlenum) = $_=~/.+\.(\d+)/;
	open(ARTICLE, "<$_");
	@articlelines = <ARTICLE>;
	close(ARTICLE);
	
	chomp( $polosa = $articlelines[11] );
	chomp( $placement = $articlelines[10] );
	chomp( $articlelines[0] );
	chomp( $articlelines[8] );
	chomp( $articlelines[9] );
	chomp( $articlelines[5] );	    
	chomp( $articlelines[29] );	    

	chomp( $articlelines[14] );
	$articlepicturecenter = "/images/$articlelines[14]";

	chomp( $articlelines[15] );
	$articlepictureuho = "/images/$articlelines[15]";
	
	    
	if( ($articlelines[5] eq 4) and ($polosa eq 3)) {
		
	    ($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="" };
	    $isselected.=" style='background-color: black; color: white' ";

	    $newsblock.="<option value=pg$articlenum $isselected>$articlelines[0]</option>\n";

	    $articlelines[9]=~s/\015//g;
	    $articlelines[9]=~s/\\/\\\\/g;
	    $articlelines[9]=~s/"/\\"/g;	
	    $articlelines[9]=~s/\012/\\n/g;

	    $articlelines[8]=~s/\\/\\\\/g;
	    $articlelines[8]=~s/"/\\"/g;	
	    $articlelines[8]=~s/\012/\\n/g;
	    
	
	    $jsblockcopy=$jsblock;
	    $jsblockcopy=~s/::jsname::/$articlelines[8]/;
	    $jsblockcopy=~s/::jstext::/$articlelines[9]/;
	    $jsblockcopy=~s/::jspicture::/$articlepicturecenter/;
	    $jsblockcopy=~s/::jspictureuho::/$articlepictureuho/;

	    $jsblockcopy=~s/::jsid::/pg$articlenum/;
	    $jsfiller.=$jsblockcopy;	
	}
    }

# ------ end of scan





# ------ getting config lines

    $sth = $dbh->prepare("select * from maket");
    $sth->execute;
    
    while( $row = $sth->fetchrow_hashref ) {
    
	if( $row->{maket_key} eq "center" ) {  $template=~s/::mycenter::/$row->{maket_data}/; }
	if( $row->{maket_key} eq "uho1" ) {  $template=~s/::myuho1::/$row->{maket_data}/; }    
	if( $row->{maket_key} eq "uho2" ) {  $template=~s/::myuho2::/$row->{maket_data}/; }
	if( $row->{maket_key} eq "uho3" ) {  $template=~s/::myuho3::/$row->{maket_data}/; }

    }




# ------ 





    $template=~s/::scriptname::/$cgipath\/edit_maket.pl/g;
    $template=~s/::newsblock::/$newsblock/;
    $template=~s/::jsblock(.+?)jsblock::/$jsfiller/gs;
    
    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;
    }


#    print "center = $formdata{mycenter}<br>uho1 = $formdata{myuho1}<br>uho2 = $formdata{myuho2}<br>uho3 = $formdata{myuho3}<br>";
#    exit;

    $sth = $dbh->prepare("update maket set maket_data=? where maket_key=?");
    
    $sth->execute( $formdata{mycenter}, "center");
    $sth->execute( $formdata{myuho1}, "uho1");
    $sth->execute( $formdata{myuho2}, "uho2");
    $sth->execute( $formdata{myuho3}, "uho3");

    $sth->finish;

#    $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;
    
    $magicteleport =~s/::whereto::/edit_maket.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;


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


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


    $sth = $dbh->prepare("select * from maket where maket_key=?");
    


    # --- Отожмем ушки :)
    local $/="\n";

    
    for( $i=1; $i<4; $i++) {
    
	$sth->execute("uho$i");
	$uhothing = $sth->fetchrow_hashref->{maket_data};
	
	if( $uhothing=~/pg/ ) {		# -- Заметка взята из пэжэ?
	
	    ($pgnumber) = $uhothing=~/pg(\d+)/;
	    $uhoblockcopy = $template;
	    
	    open(MYPGARTICLE, "</usr/local/apache/cgi-bin/pg2/base/temp.$pgnumber");
	    @pglines = <MYPGARTICLE>;
	    close(MYPGARTICLE);
	    
	    
	    $uhoblockcopy =~s/::uhosubject::/$pglines[8]/;
	    $uhoblockcopy =~s/::uhoheader::/$pglines[9]/;
	    $uhoblockcopy =~s/::uhophoto::/\/images\/$pglines[16]/;

	    $uhoblockcopy =~s/::uhourl::/\/games2000\/articles\/pg$pgnumber.shtml/g;


	    
	    $uhofiller.=$uhoblockcopy;

	} else {   # -- заметка взята из внутренней базы
	
	
	
	}    
    
    }

    open(MYCLOWN, ">$htmldir/includes/games2000_uhoblock.ssi");
    print MYCLOWN $uhofiller;
    close(MYCLOWN);
        
    chmod 0666, "$htmldir/includes/games2000_uhoblock.ssi";




    # ---  а теперь - центр :)


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

    local $/="\n";

    $sth->execute("center");
    $centerthing = $sth->fetchrow_hashref->{maket_data};
	
    if( $centerthing=~/pg/ ) {		# -- Заметка взята из пэжэ?
	    ($pgnumber) = $centerthing=~/pg(\d+)/;
	    
	    open(MYPGARTICLE, "</usr/local/apache/cgi-bin/pg2/base/temp.$pgnumber");
	    @pglines = <MYPGARTICLE>;
	    close(MYPGARTICLE);
	    
	    $template =~s/::centersubject::/$pglines[8]/;
	    $template =~s/::centerheader::/$pglines[9]/;
	    $template =~s/::centerphoto::/\/images\/$pglines[14]/;
	    $template =~s/::centerauthor::/$pglines[3]/;


	    $template =~s/::centerurl::/\/games2000\/articles\/pg$pgnumber.shtml/g;
    
    } else {   # -- заметка взята из внутренней базы
	
	
	
    }    

    open(MYCLOWN, ">$htmldir/includes/games2000_center.ssi");
    print MYCLOWN $template;
    close(MYCLOWN);
        
    chmod 0666, "$htmldir/includes/games2000_center.ssi";






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

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


