#!/usr/bin/perl

########################################################################
# COPYRIGHT NOTICE:
#
# Copyright 2001 FocalMedia.Net All Rights Reserved.
#
# Selling the code for this program without prior written consent 
# from FocalMedia.Net is expressly forbidden. You may not 
# redistribute this program in any shape or form.
# 
# This program is distributed "as is" and without warranty of any
# kind, either express or implied. In no event shall the liability 
# of FocalMedia.Net for any damages, losses and/or causes of action 
# exceed the total amount paid by the user for this software.
#
########################################################################

use Fcntl qw(:DEFAULT :flock);
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use tseek;
&get_setup;
&get_env;

$tseekdir = "$scripts_url/tseekdir.cgi";
$tseek = "$scripts_url/tseek.cgi";
$tseekrate = "$scripts_url/tseekrate.cgi";
$rate_it_cgi = "$scripts_url/rate_it.cgi";


#############################################################################################

if ($fields{'fct'} eq "") {&rate_it_screen;}
if ($fields{'fct'} eq "cast_rating") {&cast_rating;}



#############################################################################################

sub cast_rating
{

if ($fields{'rating'} > 10) { print "Content-type: text/html\n\n"; exit; } 
if ($fields{'rating'} < 1) { print "Content-type: text/html\n\n"; exit; } 


### GET COOKIES

&getCookies;

#print "Content-type: text/html\n\n";
#print "<br><br>";
#print "===> $cookies{'ID'} <br><br>";

@cids = split (/:/,$cookies{'ID'});
  foreach $item (@cids)
	{
	if ($fields{'id'} eq $item)
		{
		&vote_only_once;
		}
	}



### +1 YEAR SET COOKIE

$cr = time();
$cr = $cr + 31536000;

($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = gmtime($cr);
$year = "20" . substr($year, 1, 2);
$mon = &decode_month($mon);
$wday = &decode_weekday($wday);

$expdate = "$wday, $mday-$mon-$year 00:00:00 GMT";

$cookval = $fields{'id'} . ":" . $cookies{'ID'};

&setCookie("ID",$cookval,$expdate);



### CONTINUE

print "Content-type: text/html\n\n";

$location =  $fields{'ct'};
$location =~ s/-/\//g;
$location =~ s/-/\//g;
$location = "$data_dir/$location/contents.txt";

(@itemline) = &get_item_line ($fields{'id'}, $location);

$name = $itemline[1];
$votes = $itemline[5];
$rating = $itemline[4];

if($votes eq ""){$votes = 0;}
if($rating eq ""){$rating = 0;}

$curr = ($votes * $rating) + ($fields{'rating'});
$votes++;
$curr = $curr / $votes;
$curr = sprintf("%5.2f",$curr);

#print "VOTES: $votes <br>RATING: $rating<br>NAME: $name";
#print "<br><br> CURRENT RATING = $curr";

$icounter = $fields{'id'};

if (length($icounter) == 1) {$icounter = "000000000000" . $icounter;}
if (length($icounter) == 2) {$icounter = "00000000000" . $icounter;}
if (length($icounter) == 3) {$icounter = "0000000000" . $icounter;}
if (length($icounter) == 4) {$icounter = "000000000" . $icounter;}
if (length($icounter) == 5) {$icounter = "00000000" . $icounter;}
if (length($icounter) == 6) {$icounter = "0000000" . $icounter;}
if (length($icounter) == 7) {$icounter = "000000" . $icounter;}
if (length($icounter) == 8) {$icounter = "00000" . $icounter;}
if (length($icounter) == 9) {$icounter = "0000" . $icounter;}
if (length($icounter) == 10){$icounter = "000" . $icounter;}
if (length($icounter) == 11){$icounter = "00" . $icounter;}
if (length($icounter) == 12){$icounter = "0" . $icounter;}

$cnc = 0;


open (ITEMS, "$location");
if ($file_locking ne "No"){flock (ITEMS,LOCK_SH) or die "Can't set lock for file: $location $!\n";}
	while (defined($line=<ITEMS>))
		{
		@litems = split(/\[::\]/,$line);
			if ($icounter eq $litems[0])
				{
				
				$cnc = 0;
				$newline = "";
				
				foreach $item (@litems)
					{

					if ($cnc == 4) ## RATING
						{
						$item = $curr;
						}

					if ($cnc == 5) ### VOTES
						{
						$item = $votes;
						}
					
					$cnc++;

					$newline = $newline . $item . "[::]";
					
					}
					
					$newline = substr($newline, 0, (length($newline) - 4));
					$towrite = $towrite . $newline;

			  	}
			  	else
 			  	{
			  	$towrite = $towrite . $line;
			  	}

		}

#if ($file_locking ne "No"){flock (ITEMS,LOCK_UN);}
close (ITEMS);


open (ITEMS2, "> $location");
 if ($file_locking ne "No"){flock (ITEMS2,LOCK_EX) or die "Can't set lock for file: $location $!\n";}
	print ITEMS2 $towrite;
 #if ($file_locking ne "No"){flock (ITEMS2,LOCK_UN);}
close (ITEMS2);

$thanks = &get_template("rate_it_success.html");
$thanks =~ s/!build_url!/$build_url/g;
$thanks =~ s/!!scripts_url!!/$scripts_url/g;

print $thanks;

}







sub rate_it_screen
{

print "Content-type: text/html\n\n";

$location =  $fields{'ct'};
$location =~ s/-/\//g;
$blt_loc = $location;
$text_location = tseek::decode_dir($location);
$location = "$data_dir/$location/contents.txt";

(@itemline) = &get_item_line ($fields{'id'}, $location);

$title_with_link = "<a href=\"$tseek?id=$fields{'id'}&ct=$fields{'ct'}\" target=\"_blank\">$itemline[1]</a>";
$description = $itemline[2];
$itemurl = $itemline[3];
$rating = $itemline[4];
$votes = $itemline[5];

#print "RATING $rating";
#print "VOTES $votes";

$the_template = &get_template("rate_it.html");

if ($votes eq ""){$votes = 0;}
if ($rating eq ""){$rating = "Unrated";}

$the_template =~ s/%%title_with_link%%/$title_with_link/g;
$the_template =~ s/%%description%%/$description/g;
$the_template =~ s/%%itemurl%%/$itemurl/g;
$the_template =~ s/%%votes%%/$votes/g;
$the_template =~ s/%%rating%%/$rating/g;
$the_template =~ s/!!rate_it!!/$rate_it_cgi/g;
$the_template =~ s/!!id!!/$fields{'id'}/g;
$the_template =~ s/!!ct!!/$fields{'ct'}/g;
$the_template =~ s/!build_url!/$build_url/g;
$the_template =~ s/!!scripts_url!!/$scripts_url/g;

if ($fields{'blt'} eq "")
	{
	$text_location = "<a href=\"$scripts_url/tseekdir.cgi?location=Root-$fields{'ct'}\">$text_location</a>";
	}
	else
	{
	$text_location = "<a href=\"$build_url/$blt_loc\/\">$text_location</a>";
	}

$the_template =~ s/%%returnlink%%/$text_location/g;

print "$the_template";

}






#############################################################################################

sub get_item_line
{

my ($theid, $thelocation) = @_;

$icounter = $theid;

if (length($icounter) == 1) {$icounter = "000000000000" . $icounter;}
if (length($icounter) == 2) {$icounter = "00000000000" . $icounter;}
if (length($icounter) == 3) {$icounter = "0000000000" . $icounter;}
if (length($icounter) == 4) {$icounter = "000000000" . $icounter;}
if (length($icounter) == 5) {$icounter = "00000000" . $icounter;}
if (length($icounter) == 6) {$icounter = "0000000" . $icounter;}
if (length($icounter) == 7) {$icounter = "000000" . $icounter;}
if (length($icounter) == 8) {$icounter = "00000" . $icounter;}
if (length($icounter) == 9) {$icounter = "0000" . $icounter;}
if (length($icounter) == 10){$icounter = "000" . $icounter;}
if (length($icounter) == 11){$icounter = "00" . $icounter;}
if (length($icounter) == 12){$icounter = "0" . $icounter;}

$cnc = 0;

open (ITEMS3, "$thelocation");
if ($file_locking ne "No"){flock (ITEMS3, LOCK_SH) or die "Can't set lock for file: $thelocation $!\n";}

	while (defined($line=<ITEMS3>))
		{
		@litems = split(/\[::\]/,$line);
			if ($icounter eq $litems[0])
				{
				$ritems = $line;
			  	}
		}

#if ($file_locking ne "No"){flock (ITEMS3, LOCK_UN);}
close (ITEMS3);


@litems2 = split(/\[::\]/,$ritems);

return (@litems2);

}





sub get_env
{
if ($ENV{'QUERY_STRING'} ne "") {
								$temp = $ENV{'QUERY_STRING'};
								}
								else
								{
								read(STDIN, $temp, $ENV{'CONTENT_LENGTH'});
								}

@pairs=split(/&/,$temp);

foreach $item(@pairs) {
	($key,$content)=split (/=/,$item,2);
	$content=~tr/+/ /;
	$content=~ s/%(..)/pack("c",hex($1))/ge;
	$fields{$key}=$content;
}

$fields{'comment'}=~s/\cM//g;
$fields{'comment'}=~s/\n\n/<p>/g;
$fields{'comment'}=~s/\n/<br>/g;
}



sub get_template
{
my ($tfile) = @_;

$fsize1 = (-s "$data_dir/$tfile");
if ($fsize1 > 0)
	{
	open (DRST, "$data_dir/$tfile");
	 if ($file_locking ne "No"){flock (DRST, LOCK_SH) or die "Can't set lock for file: $data_dir/$tfile $!\n";}
		read(DRST,$rval,$fsize1);
	 #if ($file_locking ne "No"){flock (DRST, LOCK_UN);}		
	close (DRST);
	}
	else
	{
	print "Could not find <b>$data_dir/$tfile</b>";
	exit;
	}

return ($rval);
}











sub getCookies
{

	$temp2 = $ENV{'HTTP_COOKIE'};
	
	@rawCookies = split (/; /,$temp2);
	
	foreach $item2(@rawCookies)
	{
		($key, $val) = split (/=/,$item2,2);
		$cookies{$key} = $val;
	}

}





sub setCookie
{
	# end a set-cookie header with the word secure and the cookie will only
	# be sent through secure connections
	local($name, $value, $expiration, $path, $domain, $secure) = @_;
	
	print "Set-Cookie: ";
	print ($name, "=", $value, "; expires=", $expiration,
		"; path=", $path, "; ", $secure, "\n");
}


# sub setCookie
# {
# 
# local($name, $value, $expiration) = @_;
# print "Set-Cookie: $name=$value; expires=$expiration\n";
# 
#$expDate = "Saterday, 31-Dec-05 00:00:00 GMT";
#$path = "/cgi-bin/talkdungeon/d4all_2/";
#	
#}





sub getCookies
{
	
	$temp2 = $ENV{'HTTP_COOKIE'};
	
	@rawCookies = split (/; /,$temp2);
	
	foreach $item2(@rawCookies)
	{
		($key, $val) = split (/=/,$item2,2);
		$cookies{$key} = $val;
	}
	
	
}




sub decode_month
{

my ($themonth) = @_;

if ($themonth == 0) {$themonth = "Jan";}
if ($themonth == 1) {$themonth = "Feb";}
if ($themonth == 2) {$themonth = "Mar";}
if ($themonth == 3) {$themonth = "Apr";}
if ($themonth == 4) {$themonth = "Mei";}
if ($themonth == 5) {$themonth = "Jun";}
if ($themonth == 6) {$themonth = "Jul";}
if ($themonth == 7) {$themonth = "Aug";}
if ($themonth == 8) {$themonth = "Sep";}
if ($themonth == 9) {$themonth = "Oct";}
if ($themonth == 10) {$themonth = "Nov";}
if ($themonth == 11) {$themonth = "Dec";}

return ($themonth);

}


sub decode_weekday
{

my ($theweekday) = @_;

if ($theweekday == 0) {$theweekday = "Sunday";}
if ($theweekday == 1) {$theweekday = "Monday";}
if ($theweekday == 2) {$theweekday = "Tuesday";}
if ($theweekday == 3) {$theweekday = "Wednesday";}
if ($theweekday == 4) {$theweekday = "Thursday";}
if ($theweekday == 5) {$theweekday = "Friday";}
if ($theweekday == 6) {$theweekday = "Saterday";}

return ($theweekday);

}




sub vote_only_once
{

print "Content-type: text/html\n\n";

$fsize1 = (-s "$data_dir/rate_it_fail.html");
if ($fsize1 > 0)
	{
	open (DRST1, "$data_dir/rate_it_fail.html");
	 if ($file_locking ne "No"){flock (DRST1, LOCK_SH) or die "Can't set lock for file: $data_dir/rate_it_fail.html $!\n";}
		read(DRST1,$rfail,$fsize1);
	 #if ($file_locking ne "No"){flock (DRST1, LOCK_UN);}
	close (DRST1);
	}

$rfail =~ s/!build_url!/$build_url/g;
$rfail =~ s/!!scripts_url!!/$scripts_url/g;

print $rfail;
exit;

}



sub get_setup
{
#### GET CONFIGURATION ########################################################

$csize = (-s "config.cgi");
open (RVF, "config.cgi");
	read(RVF,$data_dir,$csize);
close (RVF);

$data_dir =~ s/\n//g;
$crit = chr(13); $crit =~ s/$crit//g; 
$crit = chr(10); $crit =~ s/$crit//g;

$exists = (-e "$data_dir/setup.cfg");
if ($exists > 0)
	{

	open (STP, "$data_dir/setup.cfg");
		while (defined($line=<STP>))
			{
			if ($line =~ m/#/g)
				{
				$r = pos($line);
				$line = substr($line, 0, $r - 1);
				}
				
				$line =~ s/\n//g;
			
if ($line =~ /BUILD_DIR/){$line =~ s/BUILD_DIR//g; $line =~ s/ //g; $build_dir = $line;}
if ($line =~ /BUILD_URL/){$line =~ s/BUILD_URL//g; $line =~ s/ //g; $build_url = $line;}
if ($line =~ /SCRIPTS_URL/){$line =~ s/SCRIPTS_URL//g; $line =~ s/ //g; $scripts_url = $line;}
if ($line =~ /SCRIPTS_LOC/){$line =~ s/SCRIPTS_LOC//g; $line =~ s/ //g; $scripts_loc = $line;}
if ($line =~ /ADMIN_DIRECTORY/){$line =~ s/ADMIN_DIRECTORY//g; $line =~ s/ //g; $admin_directory = $line;}
if ($line =~ /SEND_MAIL/){$line =~ s/SEND_MAIL//g; $line =~ s/ //g; $sendmail_loc = $line;}
if ($line =~ /RGST/){$line =~ s/RGST//g; $line =~ s/ //g; $thspl = $line;}
if ($line =~ /USE_MYSQL/){$line =~ s/USE_MYSQL//g; $line =~ s/ //g; $use_mysql = $line;}
if ($line =~ /DB_NAME/){$line =~ s/DB_NAME//g; $line =~ s/ //g; $db_name = $line;}
if ($line =~ /DB_USERNAME/){$line =~ s/DB_USERNAME//g; $line =~ s/ //g; $db_username = $line;}
if ($line =~ /DB_PASSWORD/){$line =~ s/DB_PASSWORD//g; $line =~ s/ //g; $db_password = $line;}
if ($line =~ /MYSQL_HOSTNAME/){$line =~ s/MYSQL_HOSTNAME//g; $line =~ s/ //g; $mysql_hostname = $line;}
if ($line =~ /MYSQL_PORT/){$line =~ s/MYSQL_PORT//g; $line =~ s/ //g; $mysql_port = $line;}
if ($line =~ /FILE_LOCKING/){$line =~ s/FILE_LOCKING//g; $line =~ s/ //g; $file_locking = $line;}
if ($line =~ /CPUSERNAME/){$line =~ s/CPUSERNAME//g; $line =~ s/ //g; $c_username = $line;}
if ($line =~ /CPPASSWORD/){$line =~ s/CPPASSWORD//g; $line =~ s/ //g; $c_password = $line;}

			}
	close (STP);
	
	}

#### END CONFIGURATION ########################################################
}


