#!/usr/bin/perl

package ppc_internal;

########################################################################
# COPYRIGHT NOTICE:
#
# Copyright 2003 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.
#
########################################################################

#### EDIT HERE -- FOR WINDOWS/IIS BASED INSTALLATIONS ONLY #######

$config_cgi = "config.cgi"; 	## <-- CHANGE THIS LINE TO THE FULL SERVER PATH TO config.cgi

# THE PATH ON A WINDOWS INSTALLATION WILL LOOK SOMETHING LIKE THIS:
# $config_cgi = "c:/inetpub/webpub/cgi-bin/pseek/config.cgi";

#### DO NOT CHANGE ANYTHING BELOW THIS LINE #################

#use FindBin;
#use lib $FindBin::Bin;
use CGI::Carp qw(fatalsToBrowser); 
use CGI::Cookie;
use CGI;
use Time::Local;
use DBI;
use LWP::Simple;
use IO::Socket;

require Exporter;
use vars qw/@ISA @EXPORT @EXPORT_OK $copyright $prgname/;

@ISA = qw(Exporter);

@EXPORT = qw(check_access
	    		get_file_contents
	    		decode_date
	    		get_date_selbox); 

@EXPORT_OK = qw($thefile
					 $drval
					 $rdvalue
					 $date_dbox);

$version = "PowerSeek SQL PPC Internal Plugin Version 1.0";

$copyright = "Copyright ©2004 FocalMedia.Net - All Rights Reserved";
$default_permissions = 0777;  ### DEFAULT PERMISSIONS THAT IS USED FOR FILES ON HOST/SERVER
$q = CGI->new;
&get_setup;
$gsettings = &new_gsettings;

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

sub dbconnect
{
	#### CONNECT TO DATABASE
	if ($mysql_hostname eq ""){$dsn = "DBI:mysql:$db_name";}else{$dsn = "DBI:mysql:$db_name:$mysql_hostname:$mysql_port";}
	$dbh = DBI->connect($dsn, $db_username, $db_password);
	if ( !defined $dbh ) {die "Cannot connect to MySQL server: $DBI::errstr\n"; }
}


sub get_date_selbox
{

my ($date_crit, $f_year, $f_month, $f_day) = @_;

my (@start_day, @start_month, @start_year);

$Sstart_year = substr($date_crit, 0, 4);
$Sstart_month = substr($date_crit, 4, 2);
$Sstart_day = substr($date_crit, 6, 2);
$date_range = $Sstart_year . "-" . $Sstart_month . "-" . $Sstart_day;

$Sstart_day = $Sstart_day - 1;
$start_day[$Sstart_day] = "selected";

$Sstart_month = $Sstart_month - 1;
$start_month[$Sstart_month] = "selected";

if ($Sstart_year eq "2005") { $start_year[2] = "selected"; }
if ($Sstart_year eq "2006") { $start_year[3] = "selected"; }
if ($Sstart_year eq "2007") { $start_year[4] = "selected"; }
if ($Sstart_year eq "2008") { $start_year[5] = "selected"; }
if ($Sstart_year eq "2009") { $start_year[6] = "selected"; }
if ($Sstart_year eq "2010") { $start_year[7] = "selected"; }

if ($Sstart_year eq "2011") { $start_year[8] = "selected"; }
if ($Sstart_year eq "2012") { $start_year[9] = "selected"; }
if ($Sstart_year eq "2013") { $start_year[10] = "selected"; }
if ($Sstart_year eq "2014") { $start_year[11] = "selected"; }
if ($Sstart_year eq "2015") { $start_year[12] = "selected"; }
if ($Sstart_year eq "2016") { $start_year[13] = "selected"; }
if ($Sstart_year eq "2017") { $start_year[14] = "selected"; }


$date_dbox = "";

if ($f_day ne "")
 {

$date_dbox = <<END_OF_DB;
      <select name="$f_day" size="1">
        <option $start_day[0] value="01" selected>1</option>
        <option $start_day[1] value="02">2</option>
        <option $start_day[2] value="03">3</option>
        <option $start_day[3] value="04">4</option>
        <option $start_day[4] value="05">5</option>
        <option $start_day[5] value="06">6</option>
        <option $start_day[6] value="07">7</option>
        <option $start_day[7] value="08">8</option>
        <option $start_day[8] value="09">9</option>
        <option $start_day[9] value="10">10</option>
        <option $start_day[10] value="11">11</option>
        <option $start_day[11] value="12">12</option>
        <option $start_day[12] value="13">13</option>
        <option $start_day[13] value="14">14</option>
        <option $start_day[14] value="15">15</option>
        <option $start_day[15] value="16">16</option>
        <option $start_day[16] value="17">17</option>
        <option $start_day[17] value="18">18</option>
        <option $start_day[18] value="19">19</option>
        <option $start_day[19] value="20">20</option>
        <option $start_day[20] value="21">21</option>
        <option $start_day[21] value="22">22</option>
        <option $start_day[22] value="23">23</option>
        <option $start_day[23] value="24">24</option>
        <option $start_day[24] value="25">25</option>
        <option $start_day[25] value="26">26</option>
        <option $start_day[26] value="27">27</option>
        <option $start_day[27] value="28">28</option>
        <option $start_day[28] value="29">29</option>
        <option $start_day[29] value="30">30</option>
        <option $start_day[30] value="31">31</option>
      </select> 
END_OF_DB
}
 
$date_dbox = $date_dbox . <<END_OF_RB;

      <select name="$f_month" size="1">
        <option $start_month[0] value="01">January</option>
        <option $start_month[1] value="02">February</option>
        <option $start_month[2] value="03">March</option>
        <option $start_month[3] value="04">April</option>
        <option $start_month[4] value="05">May</option>
        <option $start_month[5] value="06">June</option>
        <option $start_month[6] value="07">July</option>
        <option $start_month[7] value="08">August</option>
        <option $start_month[8] value="09">September</option>
        <option $start_month[9] value="10">October</option>
        <option $start_month[10] value="11">November</option>
        <option $start_month[11] value="12">December</option>
      </select> <select name="$f_year" size="1">
        <option $start_year[0] value="2003">2003</option>
        <option $start_year[1] value="2004">2004</option>
        <option $start_year[2] value="2005">2005</option>
        <option $start_year[3] value="2006">2006</option>
        <option $start_year[4] value="2007">2007</option>
        <option $start_year[5] value="2008">2008</option>
        <option $start_year[6] value="2009">2009</option>
        <option $start_year[7] value="2010">2010</option>
        
        <option $start_year[8] value="2011">2011</option>
        <option $start_year[9] value="2012">2012</option>
        <option $start_year[10] value="2013">2013</option>
        <option $start_year[11] value="2014">2014</option>
        <option $start_year[12] value="2015">2015</option>
        <option $start_year[13] value="2016">2016</option>
        <option $start_year[14] value="2017">2017</option>
      </select>

END_OF_RB

return ($date_dbox);

}






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

sub ppc_internal_search
{
	my ($key_phrase, $ppc_st, $which_search, $cache_id, $skip_number, $diff)  = @_;
	#print "===>PPC ST was: $ppc_st -- KEYPHRASE: $key_phrase -- WHICH SEARCH $which_search --  CACHEID $cache_id - SKIPNUMBER $skip_number - DIFFF $diff<BR><BR><br>";

	my ($search_results,$count);
	my @cus_details = "";
	my $temp_det = "";
	$time = time();
	$date = &decode_date($time);
	#print "==>>Date is: $date<br>";
	$internal_ppc_settings = &ppc_internal_settings;
	$ppc_numresults = 					$internal_ppc_settings->{ppc_numresults};
	$ppc_num_noresult_results = 		$internal_ppc_settings->{ppc_num_noresult_results};
	$ppc_backfill = 						$internal_ppc_settings->{ppc_backfill};
	$kanoodle_enalbled =					$internal_ppc_settings->{kanoodle_enalbled};
	$searchfeed_enalbled =				$internal_ppc_settings->{searchfeed_enalbled};
	$aff_id =								$internal_ppc_settings->{aff_id};
	$track_id =								$internal_ppc_settings->{track_id};
	$account_id =							$internal_ppc_settings->{account_id};
	$backfill =								$internal_ppc_settings->{backfill};
	$adultfilter =							$internal_ppc_settings->{adultfilter};
	$adultonly =							$internal_ppc_settings->{adultonly};
	$kan_num_noresult_results = 		$internal_ppc_settings->{kan_num_noresult_results};
	$searchfeed_num_noresult_results = $internal_ppc_settings->{searchfeed_num_noresult_results};
	$mode = 									$internal_ppc_settings->{mode};
	$manual_approve = 					$internal_ppc_settings->{manual_approve};
	$start_balance = 						$internal_ppc_settings->{start_balance};
	$min_acc_bal = 						$internal_ppc_settings->{min_acc_bal};
	
	&clean_dir();

	if ($mode == 10)
	{
		$ip = &get_ip();
	}
	else
	{
		$ip = $ENV{"REMOTE_ADDR"};
	}
	if ($which_search == 10) {$num_of_results = $ppc_num_noresult_results; } else {$num_of_results = $ppc_numresults; }

	&dbconnect;
	
	### CHECK THAT IP IS NOT BANNED
	$sql = "SELECT DISTINCT user_id FROM ppc_banned_ip WHERE ip = '$ip' order by user_id";
	$sth = $dbh->prepare($sql);
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	
	$sql1 = "SELECT * FROM ppc_keywords WHERE (keywords = '$key_phrase' OR keywords LIKE '%$key_phrase%')";
	
	#$sql1 = "SELECT DISTINCT FROM ppc_keywords WHERE (keywords = '$key_phrase' OR keywords LIKE '%$key_phrase%')";
	
	while ($my_user = $sth->fetchrow())
	{
		$sql1 .= " and user_id != '$my_user'";
	}


	
	#### CHECK USER BALANCES
	$sql = "SELECT DISTINCT id FROM ppc_users WHERE balance <= '$min_acc_bal' ORDER BY id";
	$sth = $dbh->prepare($sql);
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	#print "==> Query 2 is: $sql<br>";
	while ($my_user1 = $sth->fetchrow())
	{
		$sql1 .= " and user_id != '$my_user1' ";
	}

	
	$sql1 .= " ORDER BY link_id, bid desc";
	$sth = $dbh->prepare($sql1);
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	
	
	while (@search_details = $sth->fetchrow())
	{
		$temp_det = "";
		$temp_date = $date - $search_details[5];
		if ($temp_date > 99999999999) {$temp_date = "0" . $temp_date;}
		elsif ($temp_date > 9999999999) {$temp_date = "00" . $temp_date;}
		elsif ($temp_date > 999999999) {$temp_date = "000" . $temp_date;}
		elsif ($temp_date > 99999999) {$temp_date = "0000" . $temp_date;}
		elsif ($temp_date > 9999999) {$temp_date = "00000" . $temp_date;}
		elsif ($temp_date > 999999) {$temp_date = "000000" . $temp_date;}
		elsif ($temp_date > 99999) {$temp_date = "0000000" . $temp_date;}
		elsif ($temp_date > 9999) {$temp_date = "00000000" . $temp_date;}
		elsif ($temp_date > 999) {$temp_date = "000000000" . $temp_date;}
		elsif ($temp_date > 99) {$temp_date = "0000000000" . $temp_date;}
		elsif ($temp_date > 9) {$temp_date = "00000000000" . $temp_date;}
		elsif ($temp_date > 0) {$temp_date = "000000000000" . $temp_date;}

		if (($test_var != $search_details[1]) or ($search_details[3] =~ /\b$key_phrase\b/i))
		{
			if ($search_details[3] =~ /\b$key_phrase\b/i)
			{
				$temp_det = "bbb$search_details[4]$temp_date" . "\t" . $search_details[0] . "\t" . $search_details[1] . "\t" . $search_details[2] . "\t" . $search_details[3] . "\t" . $search_details[4] . "\t" . $search_details[5] . "\t" . "bbb" . "\t" . $temp_date; 
			}
			elsif ($test_var != $search_details[1])
			{	
				if ($search_details[3] =~ /$key_phrase/i)
				{
					$temp_det = "aaa$search_details[4]$temp_date" . "\t" . $search_details[0] . "\t" . $search_details[1] . "\t" . $search_details[2] . "\t" . $search_details[3] . "\t" . $search_details[4] . "\t" . $search_details[5] . "\t" . "aaa" . "\t" . $temp_date;
				}
			}			
		if ($temp_det ne "") { splice (@cus_details, -1, 0, $temp_det);}
		}
		$test_var = $search_details[1];
	}
	@cus_details = sort sort_criteria (@cus_details);
	#print "===>> After sorting it is: @cus_details<br>";
	
######################  

	$nr_searchres = $gsettings->{search_nrlinks_perpage};	####  Get amount of results the user wants in Powerseek
	if (($ppc_st == 0) || ($nr_searchres == 0))
	{
		$new_number = 0;
	}
	else
	{
		$new_number = $ppc_st / $nr_searchres;
	}
	if ($new_number == 0) { $ppc_st = 0; } else { $ppc_st = ($num_of_results * $new_number); }	#### if the new number is 0, else ppc_st = ppc plugin results * new amount
	foreach $customers_record (@cus_details)
	{
		@my_records = split(/[\t]+/,$customers_record);
		if ($my_records[7] eq "bbb")
		{
			$temp_aaa .= "b" . $my_records[2] . "b";
		}
	}
	$for_loop_count = 0;
	$total_results = @cus_details;

	while ($for_loop_count <= $total_results)
	{
	#	print "==>>Entering loop (for_loop_count) is: $for_loop_count<br>";
		if ($cus_details[$for_loop_count] ne "")
		{
			@my_records = split(/[\t]+/,$cus_details[$for_loop_count]);
			if ($my_records[7] eq "aaa")
			{
#				print "==>We found a AAA<br>";
				$temp_bbb = "b" . $my_records[2] . "b";
#				print "==>Temp BBB is: $temp_bbb<br>";
#				print "==>Temp AAA is: $temp_aaa<br>";
				if ($temp_aaa =~ /$temp_bbb/i)
				{
#					print "===>> Splice is: splice (cus_details, $for_loop_count, 1)<br>";
#					print "===>>Deleting Record $cus_details[$for_loop_count]<br>";
					splice (@cus_details, $for_loop_count, 1);
					$for_loop_count--;		
				}
				else {}
				$temp_aaa .= "b" . $my_records[2] . "b";
			}
		}
		else
		{
			splice (@cus_details, $for_loop_count, 1);
		}
		$for_loop_count++;
	}
	$total_results = @cus_details;
#	print "==>> Total Results in Database: $total_results<br>";
	if ($ppc_st != 0) { splice (@cus_details, 0, $ppc_st);}
	$loop_amount = 0;
	foreach $customers_record (@cus_details)
	{
		$search_links = &get_file_contents("$data_dir/ppc_tmplsearch.html");
		@my_records = split(/[\t]+/,$customers_record);
		$sql = "SELECT * FROM ppc_links WHERE id = '$my_records[2]' ";
		$sth = $dbh->prepare($sql);
		$sth->execute;
		$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
		@search_details = $sth->fetchrow();
		if ($new_number == 0) 
		{
			$result_number = ($loop_amount+1);
		} 
		else
		{
			$result_number = (($loop_amount+1) + $ppc_numresults);
		}
		
		($lastid) = &update_impressions($my_records[2], $my_records[3], $my_records[1], $key_phrase, $result_number);
		
		$clickthrough_link = qq[$script_url/ppc_clickthrough.cgi?keyword_id=$my_records[1]&result_nr=$result_number&searchphrase=$key_phrase&bid_price=$my_records[5]&link_id=];
		
		$title_link = qq[<a href="$clickthrough_link$my_records[2]&lsid=$lastid" target="_blank">$search_details[2]</a>];
#		print "==>> Link_Title is: $title_link<br>";
#		print "==>> search_details[4] is: $search_details[4], search_details[2] is: $search_details[2]<br>";
#		print  "==>> Result Number: $loop_amount<br>";
		$search_links =~ s/!!ppc_title_with_clickurl!!/$title_link/g;
#		$search_details[3] .= "Keyword ID: $my_records[1], Link ID: $my_records[2], Bid: $my_records[5], Bid Time: $my_records[6], Keyword: $my_records[4]";
		$search_links =~ s/!!ppc_description!!/$search_details[3]/g;
		$search_links =~ s/!!ppc_bidprice!!/$my_records[5]/g;
		$search_links =~ s/!!ppc_clickurl!!/$search_details[4]/g;
		$search_links =~ s/!!ppc_title!!/$search_details[2]/g;			
		$all_search_links[1] .= $search_links;
		$all_search_links[0] = "";
		$loop_amount++;
		if ($loop_amount == $num_of_results) { last;}
	}
	if ($loop_amount < $num_of_results)
	{
		if ($ppc_backfill == 11)
		{
			$number = $num_of_results - $loop_amount;    #################### $number = amount I still need to complete the user request #################
			if (($total_results == 0) || ($num_of_results == 0))
			{
				$run_from_database[0] = 0;
			}
			else
			{
				@run_from_database = split(/\./,($total_results / $num_of_results));
			}
			$page_number = $run_from_database[0] + 1;
			$ttt = $total_results;
#			print "===>>> page_number is BEFORE: $page_number<br>";
			while ($ttt > $num_of_results)
			{
				$page_number--;
				$ttt -= $num_of_results;
#				$after_delete = 10;
			}
#			print "===>>> page_number is AFTER: $page_number<br>";
#			print "===>>> number is : $number, num_of_results is: $num_of_results<br>";
			if (($kanoodle_enalbled == 11) and ($searchfeed_enalbled == 11))
			{
				@searchfeed_complete_links = &do_searchfeed("$key_phrase", $page_number, $track_id,  $account_id, $number, $skip_number, $start_number);
#				print "==>Number is: $searchfeed_complete_links[0]<br>";
				$all_search_links[1] .= $searchfeed_complete_links[1];
				if ($searchfeed_complete_links[0] < $required_number)
				{
					@kan_complete_links = &do_kanoodle("$key_phrase", $number, $aff_id, $backfill, $adultfilter, $adultonly, $skip_number, $cache_id, $page_number);
#					print "==>Number is: $kan_complete_links[0]<br>";
					$all_search_links[0] .= $kan_complete_links[2];
					$all_search_links[1] .= $kan_complete_links[1];
					$all_search_links[2] .= $kan_complete_links[0];
					$all_search_links[3] .= $kan_complete_links[3];
				}

			}
			elsif ($kanoodle_enalbled == 11)
			{
#				$skip_number = 0;
#				$number = 12;
#				print "==>> Passing to Kanoodle<br>";
#				print "==>> Parameters are: $key_phrase, $number, $aff_id, $backfill, $adultfilter, $adultonly<br>";
				@kan_complete_links = &do_kanoodle("$key_phrase", $number, $aff_id, $backfill, $adultfilter, $adultonly, $skip_number, $cache_id, $page_number);
#				print "==>Number 1 is: $kan_complete_links[0]<br>";
#				print "==>Number 2 is: $kan_complete_links[1]<br>";
#				print "==>Number 3 is: $kan_complete_links[2]<br>";
#				print "==>Line 1: $kan_complete_links[2]<br>";
#				print "==>Line 2: $kan_complete_links[1]<br>";
				$all_search_links[0] .= $kan_complete_links[2];
				$all_search_links[1] .= $kan_complete_links[1];
				$all_search_links[2] .= $kan_complete_links[0];
				$all_search_links[3] .= $kan_complete_links[3];
			}
			elsif ($searchfeed_enalbled == 11)
			{
				#$skip_number = 9;
				#$number = 29;
				#$page_number = 1;
				print "==>> Passing to Searchfeed<br>";
				print "==>> Parameters are: $key_phrase, $page_number, $track_id,  $account_id, $number, $skip_number, $diff<br>";
				@searchfeed_complete_links = &do_searchfeed("$key_phrase", $page_number, $track_id,  $account_id, $number, $skip_number, $diff);
#				print "==>Number is: $searchfeed_complete_links[0]<br>";
				$all_search_links[0] .= "";
				$all_search_links[1] .= $searchfeed_complete_links[1];
				$all_search_links[2] .= $searchfeed_complete_links[0];
			}
			return (@all_search_links);
		}
		else
		{
			return (@all_search_links);
		}
	}
	else
	{
		return (@all_search_links);
	}
}





sub update_impressions
{
	#print "==> Updating Impressions Table<br>";
	my ($link_id, $user_id, $keyword_id, $key_phrase, $nr) = @_;
	#### CONNECT TO DATABASE
	$ip = $ENV{"REMOTE_ADDR"};
	if ($mysql_hostname eq ""){$dsn2 = "DBI:mysql:$db_name";}else{$dsn2 = "DBI:mysql:$db_name:$mysql_hostname:$mysql_port";}
	$dbh2 = DBI->connect($dsn2, $db_username, $db_password);
	if ( !defined $dbh2 ) {die "Cannot connect to MySQL server: $DBI::errstr\n"; }
	$sql2 = "INSERT into ppc_impressions set link_id = '$link_id',
									user_id = '$user_id',
									keyword_id = '$keyword_id',
									result_nr = '$nr',
									searchphrase = '$key_phrase'";
									
	$sth2 = $dbh2->prepare($sql2);
	$sth2->execute;
	$serror = ""; $serror = $sth2->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql2";}
	
	$insertid = $dbh2->{'mysql_insertid'};
	#print "===> $insertid<BR>";
	
	return ($insertid);

}






sub update_clickthrough
{
	my ($link_id, $keyword_id, $result_nr, $searchphrase, $ip, $bid_price, $my_code)  = @_;
	my $sourcedir = "$data_dir/searchcache";
	$query = new CGI;
	
	&dbconnect;
	
	### GET LINK URL
	$sql = "select user_id, url from ppc_links where id = '$link_id'";
	$sth = $dbh->prepare($sql);
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	@link_detail = $sth->fetchrow();

	### IF IP IS A VALID INTERNET ADDRESS
	if ($my_code ne "Return")
	{
	
		$temp_filename = "click_" . $ENV{"REMOTE_ADDR"} . ".dat";
		#open (KOOS , "> $data_dir/koos123.dat");
		
		### CHECK IF A USER HAS NOT CLICKED/VISITED THIS URL BEFORE (CHECK FOR COOKIE)
		$value = $query->cookie('PPC_click');

		#print "Content-type: text/html\n\n";
		#print "==> $value --- $my_code"; exit;

		### CHECK IF WE HAVE CACHED THE IP ADDRESS IF CLICKED IN THE PAST
		if ((-e "$sourcedir/$temp_filename") == 1)
		{
			$filesize = (-s "$sourcedir/$temp_filename");
			open (GET_COUNT , "$sourcedir/$temp_filename");
			read(GET_COUNT,$value,$filesize);
			close(GET_COUNT);
		}

		$compare_link = "a" . $link_id . "a";


		### SET COOKIE IF NO COOKIE PRESENT
		if ($value eq "")
		{
			$new_link = "aaa" . $link_id . "aaa";
			
			$ppc_cookie = $query->cookie(-name=>'PPC_click',
										  -value=>$new_link,
										  -expires=>'+24h',
										  -path=>'/');
			print $query->header(-cookie=>[$ppc_cookie]); 
			
			$cookie_set = $query->cookie('PPC_click');
			
			if ($cookie_set eq "")
			{
				open (TEMPDATA, "> $sourcedir/$temp_filename");
				print TEMPDATA "$new_link";
				close(TEMPDATA);
				$stat = chmod($default_permissions,"$sourcedir/$temp_filename","$sourcedir/$temp_filename");
			}
			$flag = 10;
			$return_detail[0] = 10;
		}

			
			##############
			#$ppc_cookie = $query->cookie(-name=>'PPC_click',
			#							  -value=>'',
			#							  -expires=>'+24h',
			#							  -path=>'/');
			#print $query->header(-cookie=>[$ppc_cookie]); 
			#
			#print "Content-type: text/html\n\n";
			#print "<BR><BR>==> $value --- $compare_link"; exit;
			##############
			#$value = ""; $compare_link = "12344";


			#### IF USER HAS ALREADY CLICKED THIS LINK DON'T RECORD IT
			if ($value =~ /$compare_link/i)
			{
				$return_detail[1] = $link_detail[1];
				return(@return_detail);
			}
			else ### IF IT'S A NEW CLICK (USER HAS NOT CLICKED WITHIN 24 HOURS)
			{

				if ($ip eq "")
				{
					$ip = $ENV{"REMOTE_ADDR"};
				}
			
				if ($mysql_hostname eq ""){$dsn2 = "DBI:mysql:$db_name";}else{$dsn2 = "DBI:mysql:$db_name:$mysql_hostname:$mysql_port";}
				$dbh2 = DBI->connect($dsn2, $db_username, $db_password);
				if ( !defined $dbh2 ) {die "Cannot connect to MySQL server: $DBI::errstr\n"; }
			
				$sql2 = "select distinct ip from ppc_admin_banned_ip where ip = '$ip' ";
				$sth2 = $dbh2->prepare($sql2);
				$sth2->execute;
				$serror1 = ""; $serror1 = $sth2->errstr; if ($serror1 ne "") {die "SQL Syntax Error: $serror1 \n From: $sql2";}
				$rows = $sth2->rows();
			
					if ($rows > 0)
					{}
					else ### RECORD CLICK
					{
					$sql = " INSERT INTO ppc_clickthrough SET	link_id = '$link_id',
														user_id = '$link_detail[0]',
														keyword_id = '$keyword_id',
														result_nr = '$result_nr',
														searchphrase = '$searchphrase', 
														ip = '$ip',
														bid_price = '$bid_price'";
					
					
					#print "Content-type: text/html\n\n";
					#print "==> $sql"; exit;
					
					$sth = $dbh->prepare($sql);
					$sth->execute;
					$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
					$time = time();
					$cl_date = &decode_date($time,1);
					$sql = "insert into ppc_payments Values (NULL, '$link_detail[0]', '$bid_price', NULL, NULL, 'Click Through on $cl_date', 'minus' , 'N')";
					$sth = $dbh->prepare($sql);
					$sth->execute;
					$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
					$sql = "update ppc_users set balance = (balance - '$bid_price') where id = '$link_detail[0]'";
					$sth = $dbh->prepare($sql);
					$sth->execute;
					$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
					}	



				if ( $flag != 10) ### SET COOKIE IF NO COOKIE WAS PRESENT
				{
					$link_id =  $value . $link_id . "aaa" ;
					$ppc_cookie = $query->cookie(-name=>'PPC_click',
												  -value=>$link_id,
												  -expires=>'+24h',
												  -path=>'/');
					print $query->header(-cookie=>[$ppc_cookie]); 
					$cookie_set = $query->cookie('PPC_click');

					if ($cookie_set eq "")
					{
						open (TEMPDATA, "> $sourcedir/$temp_filename");
						print TEMPDATA "$link_id";
						close(TEMPDATA);
						$stat = chmod($default_permissions,"$sourcedir/$temp_filename","$sourcedir/$temp_filename");
					}
					$return_detail[0] = 10;
				}
		}
		$return_detail[1] = $link_detail[1];
		return(@return_detail);
	}
	else
	{
		return($link_detail[1]);
	}

}









sub do_kanoodle
{	
	print "==>Doing Kanoodle<br>";
	my ($keywords, $number, $aff_id, $backfill, $adultfilter, $adultonly, $skip_number, $cache_id, $page_number)  = @_;
	print "==>Getting: my ($keywords, $number, $aff_id, $backfill, $adultfilter, $adultonly, $skip_number, $cache_id, $page_number)<br>";
	$real_count = 0;
	if ($page_number == 1)
	{
		$page_number = 0;
	}
	else
	{
		$page_number -= 1;
		$page_number *= 10;
	}
	if ($mode == 10)
	{
		$ip = &get_ip();
	}
	else
	{
		$ip = $ENV{"REMOTE_ADDR"};
	}
	if ($cache_id eq "")
	{
		$cache_id = &clean_dir(10);
		$cache_filename = "$keywords" . "-" . $cache_id . ".dat";
	}
	else
	{
		$cache_filename = "$keywords" . "-" . $cache_id . ".dat";
	}
	open (DATA, ">> $data_dir/searchcache/$cache_filename");
#	print "==>Counter is: $counter<br>";
#	print "==>Filename is: $cache_filename<br>";
#	print "==>>Skip Amount is: $skip_number<br>";
	$numresults = $number + $skip_number;
#	$number = 1;
	if ($skip_number eq "") 
	{
		$skip_number = 0;
	}
	if ($number eq "") 
	{
		$number = 0;
	} 
		$pass_string = "http://partner1.kanoodle.com/cgi-bin/partner.cgi?query=$keywords&searchip=$ip&id=$aff_id&numresults=10&first=$page_number&format=xml1";
#		print "Passtring is: $pass_string<br>";
		if ($backfill == 11) {$pass_string .= "&backfill=1";}
		if ($adultfilter == 10) {$pass_string .= "&adultfilter=1";}
		if ($adultonly == 11) {$pass_string .= "&adultonly=1";}

		print "Passtring is: $pass_string<br>";
		$txt = get("$pass_string");
		print "GET String is: $txt<br>";
		print DATA "$txt\n";
		close(DATA);		
		$stat = chmod($default_permissions,"$data_dir/searchcache/$cache_filename","$data_dir/searchcache/$cache_filename");
		if ((-e "$data_dir/searchcache/$cache_filename") == 1)
		{
			$filesize = (-s "$data_dir/searchcache/$cache_filename");
			open (GET_COUNT , "$data_dir/searchcache/$cache_filename");
			read(GET_COUNT,$txt,$filesize);
			close(GET_COUNT);
		}
		if ($txt eq "")
		{
			$txt = qq[&nbsp;];
			#$txt = qq[<p><font color="#FF0000" face="$font" size="3">Remote server could not be reached. $heading will not be displayed.</font></p>];
		}
		else
		{
#			open (KAN_LOG, "> $data_dir/Kanoodle_log.dat");
#			print KAN_LOG "Returned Results are: $txt\n";
			$recorder = 0;
			$tag = "record";
			$tag1 = "title";
			$tag2 = "url";
			$tag3 = "description";
			$tag4 = "bidprice";
			$tag5 = "clickurl";
			@records = split(/<\s*\/$tag\s*>/i, $txt);
#			print KAN_LOG "After a Split Records are: @records\n";
			$to_escape_string = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>";                                                               
			$to_escape_string1 = "<record>";
			$to_escape_string2 = "<title><![CDATA[";
			$to_escape_string3 = "<url><![CDATA[";
			$to_escape_string4 = "<description><![CDATA[";
			$to_escape_string5 = "<bidprice><![CDATA[";
			$to_escape_string6 = "<clickurl><![CDATA[";
			$to_escape_string7 = "]]>";
			$to_escape_string = quotemeta($to_escape_string);
			$to_escape_string1 = quotemeta($to_escape_string1);
			$to_escape_string2 = quotemeta($to_escape_string2);
			$to_escape_string3 = quotemeta($to_escape_string3);
			$to_escape_string4 = quotemeta($to_escape_string4);
			$to_escape_string5 = quotemeta($to_escape_string5);
			$to_escape_string6 = quotemeta($to_escape_string6);
			$to_escape_string7 = quotemeta($to_escape_string7);
			$records[$recorder] =~ s/$to_escape_string//ig;
#			print KAN_LOG "After some Cutting Record is: $records[$recorder]\n";
#			close (KAN_LOG);
			$fixed_skip = $skip_number;
			while ($recorder < $numresults)
			{
				print "==>>while ($recorder < $numresults)<br>";
				if ($skip_number != 0)
				{$skip_number--; $recorder++;}
				else
				{				
					print "==>>Inside the while for processing<br>";
					$kan_search_links = &get_file_contents("$data_dir/ppc_tmplsearch.html");
					@title = "";
					@url = "";
					@description = "";
					@bidprice = "";
					@clickurl = "";
					$records[$recorder] =~ s/\n//ig;
					if ($recorder == 0)
					{
						@title = split(/<\s*\/$tag1\s*>/i, $records[$recorder]);
						@url = split(/<\s*\/$tag2\s*>/i, $title[$recorder+1]);
						@description = split(/<\s*\/$tag3\s*>/i, $url[$recorder+1]);
						@bidprice = split(/<\s*\/$tag4\s*>/i, $description[$recorder+1]);
						@clickurl = split(/<\s*\/$tag5\s*>/i, $bidprice[$recorder+1]);
					}
					else
					{
						if ($recorder == 1) {$count = 0;}
						if ($recorder == 2) {$count = 1;}
						if ($recorder == 3) {$count = 2;}
						if ($recorder == 4) {$count = 3;}
						if ($recorder == 5) {$count = 4;}
						if ($recorder == 6) {$count = 5;}
						if ($recorder == 7) {$count = 6;}
						if ($recorder == 8) {$count = 7;}
						if ($recorder == 9) {$count = 8;}
						if ($recorder == 10) {$count = 9;}
						if ($recorder == 11) {$count = 10;}
						if ($recorder == 12) {$count = 11;}
						if ($recorder == 13) {$count = 12;}
						if ($recorder == 14) {$count = 13;}
						if ($recorder == 15) {$count = 14;}
						if ($recorder == 16) {$count = 15;}
						if ($recorder == 17) {$count = 16;}
						if ($recorder == 18) {$count = 17;}
						if ($recorder == 19) {$count = 18;}
						if ($recorder == 20) {$count = 19;}
						@title = split(/<\s*\/$tag1\s*>/i, $records[$recorder]);
						@url = split(/<\s*\/$tag2\s*>/i, $title[$recorder-$count]);
						@description = split(/<\s*\/$tag3\s*>/i, $url[$recorder-$count]);
						@bidprice = split(/<\s*\/$tag4\s*>/i, $description[$recorder-$count]);
						@clickurl = split(/<\s*\/$tag5\s*>/i, $bidprice[$recorder-$count]);
					}
					$title[0] =~ s/\n//ig;
					$url[0] =~ s/\n//ig;
					$description[0] =~ s/\n//ig;
					$bidprice[0] =~ s/\n//ig;
					$clickurl[0] =~ s/\n//ig;
					$title[0] =~ s/$to_escape_string1//ig;
					$title[0] =~ s/$to_escape_string2//ig;
					$url[0] =~ s/$to_escape_string3//ig;
					$description[0] =~ s/$to_escape_string4//ig;
					$bidprice[0] =~ s/$to_escape_string5//ig;
					$clickurl[0] =~ s/$to_escape_string6//ig;
					$title[0] =~ s/$to_escape_string7//ig;
					$url[0] =~ s/$to_escape_string7//ig;
					$description[0] =~ s/$to_escape_string7//ig;
					$bidprice[0] =~ s/$to_escape_string7//ig;
					$clickurl[0] =~ s/$to_escape_string7//ig;		
					$title_link = qq[<a href="$clickurl[0]" target="_blank">$title[0]</a>];
					if (($title[0] ne "") && ($description[0] ne ""))
					{
						$real_count++;
						$kan_search_links =~ s/!!ppc_title_with_clickurl!!/$title_link/g;
						$kan_search_links =~ s/!!ppc_description!!/$description[0]/g;
						$kan_search_links =~ s/!!ppc_bidprice!!/$bidprice[0]/g;
						$kan_search_links =~ s/!!ppc_clickurl!!/$clickurl[0]/g;
						$kan_search_links =~ s/!!ppc_title!!/$title[0]/g;			
						$all_kan_links .= $kan_search_links;
					}
					$recorder++;
				}
			}
		}
		if ($real_count != $numresults)
		{
			$default_permissions = 0400;
			$stat = chmod($default_permissions,"$data_dir/searchcache/$cache_filename","$data_dir/searchcache/$cache_filename");
		}
		$all_kan_links1[0] = $real_count + $fixed_skip;    #### Next ####
		$all_kan_links1[1] = $all_kan_links;			#### Results ####
		$all_kan_links1[2] = $cache_id;				#### Cache File ID ####
		$all_kan_links1[3] = $fixed_skip;				#### Backfill Number ####
		$all_kan_links1[4] = $real_count;			#### Real Amount of Links Displayed ####
#		print "==> All Data: @all_kan_links1<br>";
		return (@all_kan_links1);
}
	




sub do_searchfeed
{

	my ($keywords, $number, $track_id,  $account_id, $searchfeed_numresults, $skip_number, $diff)  = @_;

	print "==>Doing SearchFeed<br>";	
	print "==>Getting in: my ($keywords, $number, $track_id,  $account_id, $searchfeed_numresults, $skip_number, $diff)<br>";
	if ($mode == 10)
	{
		$ip = &get_ip();
	}
	else
	{
		$ip = $ENV{"REMOTE_ADDR"};
	}
	print "==> IP is: $ip<br>";
	if ($number eq "") 
	{
		$number = 0;
	} 
	if ($skip_number eq "") 
	{
		$skip_number = 0;
	} 
	
		### GET CURRENT PAGE NUMBER
		
		$cst = $q->param('st');
		$cnd = $q->param('nd');
	
		$resultsppage = $cnd - $cst;
		$the_current_page = $cnd  / $resultsppage;
	
		$pass_string = "http://www.searchfeed.com/rd/feed/TextFeed.jsp?trackID=$track_id&pID=$account_id&cat=$keywords&nl=$searchfeed_numresults&page=$the_current_page&ip=$ip";
		print "String to pass is: $pass_string<br>";
		$txt = get("$pass_string");
#		print "After GET: $txt<br>";
		if ($txt eq "")
		{
			$all_searchfeed_links1[0] = 0;
			$all_searchfeed_links1[1] = "";
			return (@all_searchfeed_links1);
		}
		else
		{
			@records = split(/\|/,$txt);
			$my_count = 0;
			@title = "";
			@url = "";
			@description = "";
			@bid = "";
			@uri = "";
			foreach $record_detail (@records)
			{
				if ($record_detail =~ m/Title/ig) {splice (@title, -1, 0, $records[$my_count+2]);}
				if ($record_detail =~ m/URL/ig) {splice (@url, -1, 0, $records[$my_count+2]);}
				if ($record_detail =~ m/URI/ig) {splice (@uri, -1, 0, $records[$my_count+2]);}
				if ($record_detail =~ m/Description/ig) {splice (@description, -1, 0, $records[$my_count+2]);}
				if ($record_detail =~ m/Bid/ig) {splice (@bid, -1, 0, $records[$my_count+2]);}
				$my_count++;
			}
			print "==>>We found: $my_count Results<br>";
			$my_count = 0;
			if ($skip_number != 0) { splice (@records, 0, $skip_number); $searchfeed_numresults -= $skip_number;}
			print "==>>We have deleted: $skip_number Results<br>";
			while ($my_count < $searchfeed_numresults)
			{
				$searchfeed_search_links = &get_file_contents("$data_dir/ppc_tmplsearch.html");
				$title_link = qq[<a href="$uri[$my_count]" target="_blank">$title[$my_count]</a>];
				if (($title[$my_count] ne "") && ($description[$my_count] ne ""))
				{
					$searchfeed_search_links =~ s/!!ppc_title_with_clickurl!!/$title_link/g;
					$searchfeed_search_links =~ s/!!ppc_description!!/$description[$my_count]/g;
					$searchfeed_search_links =~ s/!!ppc_bidprice!!/$bid[$my_count]/g;
					$searchfeed_search_links =~ s/!!ppc_clickurl!!/$uri[$my_count]/g;
					$searchfeed_search_links =~ s/!!ppc_title!!/$title[$my_count]/g;			
					$all_searchfeed_links .= $searchfeed_search_links;
				}
				$my_count++;
			}
			print "==>>We have processed: $my_count Results<br>";
			$all_searchfeed_links1[0] = $my_count;
			$all_searchfeed_links1[1] = $all_searchfeed_links;
			return (@all_searchfeed_links1);
		}
}





sub get_setup
{
	$exists = (-e "$config_cgi");
	if ($exists > 0)
	{
		open (STP, "$config_cgi");
		while (defined($line=<STP>))
		{
			if ($line =~ m/#/g)
			{
				$r = pos($line);
				$line = substr($line, 0, $r - 1);
			}
			$line =~ s/\n//g;
			if ($line =~ /^DB_NAME/){$db_name = &get_setup_line2($line, DB_NAME);}
			if ($line =~ /^DB_USERNAME/){$db_username = &get_setup_line2($line, DB_USERNAME);}
			if ($line =~ /^DB_PASSWORD/){$db_password = &get_setup_line2($line, DB_PASSWORD);}
			if ($line =~ /^MYSQL_HOSTNAME/){$mysql_hostname = &get_setup_line2($line, MYSQL_HOSTNAME);}
			if ($line =~ /^MYSQL_PORT/){$mysql_port = &get_setup_line2($line, MYSQL_PORT);}
			if ($line =~ /^SCRIPT_URL/){$script_url = &get_setup_line2($line, SCRIPT_URL);}
			if ($line =~ /^ADMIN_URL/){$admin_url = &get_setup_line2($line, ADMIN_URL);}
			if ($line =~ /^WEB_URL/){$web_url = &get_setup_line2($line, WEB_URL);}
			if ($line =~ /^WEB_DIR/){$web_dir = &get_setup_line2($line, WEB_DIR);}
			if ($line =~ /^DATA_DIR/){$data_dir = &get_setup_line2($line, DATA_DIR);}
			if ($line =~ /^USERNAME/){$username = &get_setup_line2($line, USERNAME);}
			if ($line =~ /^PASSWORD/){$password = &get_setup_line2($line, PASSWORD);}
			if ($line =~ /^MAIL_METHOD/){$mail_method = &get_setup_line2($line, MAIL_METHOD);}
			if ($line =~ /^SENDMAIL/){$sendmail = &get_setup_line2($line, SENDMAIL);}
			if ($line =~ /^SMTP_SERVER/){$smtp_server = &get_setup_line2($line, SMTP_SERVER);}
		}
		close (STP);
	}
}


sub get_setup_line2
{
	my ($setup_line, $setup_var) = @_;
	$crit = "\"";
	$setup_line =~ m/$crit/g;
	$r1 = pos($setup_line);
	$setup_line =~ m/$crit/g;
	$r2 = pos($setup_line);
	$setup_line = substr($setup_line, $r1, ($r2 - $r1 - 1));
	$return_val = $setup_line;
	return ($return_val);
}



sub ppc_settings
{
	my $this = {};
	$scnts = &get_file_contents("$data_dir/ppc_error_messages.dat");
	@all_obj_items = split (/\n/, $scnts);
	foreach $obji (@all_obj_items)
	{
		($obj_prp, $obj_val) = split (/=/, $obji);
		$this->{$obj_prp} = $obj_val;
	}
	bless $this;
	return $this;
}




sub ppc_internal_settings
{
	my $this = {};
	$scnts = &get_file_contents("$data_dir/ppc_settingsm.dat");
	@all_obj_items = split (/\n/, $scnts);
	foreach $obji (@all_obj_items)
	{
		($obj_prp, $obj_val) = split (/=/, $obji);
		$this->{$obj_prp} = $obj_val;
	}
	bless $this;
	return $this;
}


sub get_file_contents
{
	my ($filename) = @_;
	my ($filesize, $thefile);
	if ((-e "$filename") > 0) 
	{
		$filesize = (-s "$filename");
		open (TFILECNTS, "$filename") || die "$filename";
			read(TFILECNTS,$thefile,$filesize);
		close (TFILECNTS);
	}
	return ($thefile);
}

sub new_gsettings
{
	my $this = {};
	my ($scnts, @all_obj_items, $obji, $obj_prp, $obj_val);
	$scnts = &get_file_contents("$data_dir/gsettings.dat");
	@all_obj_items = split (/\n/, $scnts);
	foreach $obji (@all_obj_items)
	{
		($obj_prp, $obj_val) = split (/=/, $obji);
		$this->{$obj_prp} = $obj_val;
	}
	bless $this;
	return $this;
}

sub get_ip
{
	return ("192.168.1.1");
}

sub sort_criteria 
{
	if ($a gt $b) 
	{
		$retval = -1;
	} 
	elsif ($a eq $b) 
	{
		$retval = 0;
        } 
        else
        {
		$retval = 1;
        }
        $retval;
}






sub clean_dir
{
	my ($return_mode) = @_;
	my $sourcedir = "$data_dir/searchcache";
	@deletelist = "";
	$delete_age_cache = "7200";
	$delete_age_cookie = "86400";
	if ((-e "$sourcedir") != 1)
	{
		mkdir ("$sourcedir", 0777);
		open (COUNTER, "> $sourcedir/counter");
		print COUNTER "0" . "\n";
		close(COUNTER);
		$stat = chmod($default_permissions,"$sourcedir/counter","$sourcedir/counter");
	}
	else
	{
		if ($return_mode == 10)
		{
			if ((-e "$sourcedir/counter") == 1)
			{
				$filesize = (-s "$sourcedir/counter");
				open (GET_COUNT , "$sourcedir/counter");
				read(GET_COUNT,$counter,$filesize);
				close(GET_COUNT);
				$counter++;
				open (COUNTER, "> $sourcedir/counter");
				print COUNTER "$counter" . "\n";
				close(COUNTER);
				$stat = chmod($default_permissions,"$sourcedir/counter","$sourcedir/counter");
			}
			else
			{
				open (COUNTER, "> $sourcedir/counter");
				print COUNTER "0" . "\n";
				close(COUNTER);
				$stat = chmod($default_permissions,"$sourcedir/counter","$sourcedir/counter");
				$counter = 0;
			}
		}	
	}
	if ($return_mode != 10)
	{
		opendir(CACHEDIR, "$sourcedir/") || die ("Unable to open Search Cache Directory");
		while ($filename = readdir(CACHEDIR)) 
		{
			if (($filename ne ".") and ($filename ne "..") and ($filename ne "counter"))
			{
				if (substr($filename, 0, 6) eq "click_")
				{
					if ((time() - (stat($sourcedir."/".$filename))[9]) > $delete_age_cookie)
					{
						splice (@deletelist, -1, 0, $filename);
					}
				}
				else
				{
					if ((time() - (stat($sourcedir."/".$filename))[9]) > $delete_age_cache)
					{
						splice (@deletelist, -1, 0, $filename);
					}
				}
			}
		}
		closedir(CACHEDIR);
		if (@deletelist)
		{
			chdir ($sourcedir);
			unlink (@deletelist)
		}
	}
	if ($return_mode == 10)
	{
		return ($counter)
	}
}







sub get_help_tab
{
	my ($the_filename) = @_;
	my ($template);
	if ((-e "$data_dir/$the_filename") > 0) 
	{
		$template = &get_file_contents("$data_dir/ppc_link_style.html");
		$template =~ s/!!script_url!!/$script_url/g;
		$template =~ s/!!filename!!/$the_filename/g;
	}
	else
	{
		$template = qq[&nbsp;];
	}
	return ($template);
}

sub decode_date
{
	my ($tvalue, $type) = @_;
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst,@marray, $rdvalue, $ampm);
	@marray = ("January", "Febraury", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime($tvalue);
	$year = "20" . substr($year, 1, 2);
	if (length($hour) == 1) {$hour = "0" . $hour;}
	if (length($hour) == 1) {$hour = "0" . $hour;}
	if (length($min) == 1) {$min = "0" . $min;}
	if (length($min) == 1) {$min = "0" . $min;}
	if (length($sec) == 1) {$sec = "0" . $sec;}
	if (length($sec) == 1) {$sec = "0" . $sec;}
	if ($hour == 0){$hour = 12;}
	$mon++;
	if (length($mday) == 1) { $mday = "0" . $mday; }
	if (length($mon) == 1) { $mon = "0" . $mon; }
	$rdvalue = "$year$mon$mday$hour$min$sec";
	if ($type == 1)
	{
		if ($mon == 1) {$mon = $marray[0];}
		if ($mon == 2) {$mon = $marray[1];}
		if ($mon == 3) {$mon = $marray[2];}
		if ($mon == 4) {$mon = $marray[3];}
		if ($mon == 5) {$mon = $marray[4];}
		if ($mon == 6) {$mon = $marray[5];}
		if ($mon == 7) {$mon = $marray[6];}
		if ($mon == 8) {$mon = $marray[7];}
		if ($mon == 9) {$mon = $marray[8];}
		if ($mon == 10) {$mon = $marray[9];}
		if ($mon == 11) {$mon = $marray[10];}
		if ($mon == 12) {$mon = $marray[11];}
		$rdvalue = $mday . " " . $mon . " " . $year . " at " . $hour . "h" . $min;
	}
	return ($rdvalue);
}

sub send_email
{
	my($sendername1, $fromemail1, $toemail1, $mail_subject1, $email_message1) = @_;

	if ($mail_method eq "smtp")
	{
		&send_mail_smtp($toemail1, $fromemail1, $sendername1, $mail_subject1, $email_message1, $smtp_server);
	}
	else
	{
		&send_mail_sendmail ($sendername1, $fromemail1, $toemail1, $mail_subject1, $email_message1);
	}
}


sub send_mail_sendmail
{
	# REQUIRES 
	#  - location of sendmail
	#  - name
	#  - from email
	#  - to email address
	#  - subject
	#  - message

	my($sendername, $fromemail, $toemail, $mail_subject, $email_message) = @_;
	my ($ftext);

	$sendername =~ s/\n//g;
	$fromemail =~ s/\n//g;
	$toemail =~ s/\n//g;
	$mail_subject =~ s/\n//g;

	### check for attacks

	$toemail =~ s/\;//g;
	$toemail =~ s/^\s+//g;
	$toemail =~ s/\s+$//g;
	if ($toemail =~ /^\S+\@\S+$/)
	{
		$ftext = "<" . "$fromemail" . ">";
open (SENDMAIL, "| $sendmail $toemail");
print SENDMAIL <<End_of_Mail;
From: $sendername $ftext
To: $toemail
Reply-To: $fromemail
Subject: $mail_subject
Sender: $fromemail

$email_message

End_of_Mail
	}
}


sub send_mail_smtp
{
	my ($to_email, $from_email, $from_name, $email_subject, $email_msg, $smtp_server_ss) = @_;
	use IO::Socket;

	$remote = IO::Socket::INET->new(	Proto => "tcp",
				      				PeerAddr  => $smtp_server_ss,
				      				PeerPort  => 25);

	unless ($remote)
	{
		print "Connection failed when trying to connect to $smtp_server_ss";
		$TCPconnect = "False";
		exit;
	}

	if ($TCPconnect ne "False")
	{

	   $remote->autoflush(1);

		send($remote, "HELO localhost\n", 0);
		recv($remote, $buffer, 200, 0);
		if ($buffer !~ /220/) { $remote_error = $buffer; }
		#print "HELO localhost -> $buffer <Br><Br>";

		if ($remote_error eq "")
		{
		send($remote, "MAIL From: <$from_email>\n", 0);
		recv($remote, $buffer, 200, 0);
		if ($buffer !~ /250/) { $remote_error = $buffer; }
		#print "MAIL From [$from_email] -> $buffer <Br><Br>";
		}

		if ($remote_error eq "")
		{
		send($remote, "RCPT To: <$to_email>\n", 0);
		recv($remote, $buffer, 200, 0);
		if ($buffer !~ /250/) { $remote_error = $buffer; }
		#print "RCPT To: [$to_email] -> $buffer <Br><Br>";
		}

		if ($remote_error eq "")
		{
		send($remote, "DATA\n", 0);
		recv($remote, $buffer, 200, 0);
		if ($buffer !~ /250/) { $remote_error = $buffer; }
		#print "DATA -> $buffer <Br><Br>";
		}

		send($remote, "From: $from_name\n", 0);
		send($remote, "Subject: $email_subject\n", 0);

		send($remote, $email_msg, 0);

		send($remote, "\r\n.\r\n", 0);
		send($remote, "QUIT\n", 0);

	close $remote;
	}
}






sub check_access
{
my ($EnteredUser, $EnteredPass, $luid, $loginp) = @_;
my ($usercookie, $passcookie, $query);

$query = new CGI;
$usercookie = $query->cookie('nuser1');
$passcookie = $query->cookie('npass1');
$useridcookie = $query->cookie('userid1');

### IF COOKIE HAS ALREADY BEEN SET
if ((length($usercookie) > 1) and (length($passcookie) > 1))
	{
	#print "Content-type: text/html\n\n";
	#print "IDDDD: $loginp--- $useridcookie <BR><BR>";
	
	if ($loginp eq "LOGIN")
		{
		$the_id = $useridcookie;
		}
		else
		{
		if ($q->param('id') ne "") { $the_id = $q->param('id'); }
		if ($q->param('user_id') ne "") { $the_id = $q->param('user_id'); }
		}
		
	if ($the_id eq "") 
			{
			print "Content-type: text/html\n\n";
			print "NO ID -- $the_id -- $loginp";
			exit;
			}
	
	&dbconnect;
	$sql = "SELECT username, password, id FROM ppc_users WHERE (username = '$usercookie') AND (password = '$passcookie') AND (id = '$the_id') AND (active != 'N') ";
	$sth = $dbh->prepare($sql);	
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	$rows = $sth->rows();
	$sth->finish;
	$dbh->disconnect; 
	if ($rows != 1)  {&wrong_ps; exit;}
	
	#print "Content-type: text/html\n\n";
	#print "FISHING!";
	#exit;
	
	} ### IF USER IS LOGGING IN
elsif (($EnteredUser ne "") and ($EnteredPass ne ""))
	{
	&dbconnect;
	$sql = "SELECT username, password, id FROM ppc_users WHERE username = '$EnteredUser' AND password = '$EnteredPass' AND (active != 'N')";
	$sth = $dbh->prepare($sql);
	if ( !defined $dbh ) {die "Cannot connect to mSQL server: $DBI::errstr\n"; }
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror";} 
	$rows = $sth->rows();
	
	while ( @row = $sth->fetchrow() ) 
		{
		$the_id = $row[2];
		}
		
	$sth->finish;
	$dbh->disconnect; 
	
	if ($rows != 1) {&wrong_ps; exit;}
	&do_login($EnteredUser,$EnteredPass,$the_id);
	
	}
else ### PRINT LOGIN SCREEN
	{
	print "Content-type: text/html\n\n";
	my ($message) = @_;
	if ($message eq "") {$message = "&nbsp;"};
	$template = get_file_contents("$data_dir/ppc_user_login.html");
	$ppc_url = qq[$script_url/ppc_login.cgi];
	$pass_link = qq[$script_url/ppc_login.cgi?fct=forgot];
	$username = qq[<input type="text" name="username" size="20">];
	$password  = qq[<input type="password" name="password" size="20">];
	$template =~ s/!!ppc_url!!/$ppc_url/g;
	$template =~ s/!!username!!/$username/g;
	$template =~ s/!!password!!/$password/g;
	$template =~ s/!!error_message!!/$message/g;
	$template =~ s/!!web_url!!/$web_url/g;
	$template =~ s/!!forgot_pass_link!!/$pass_link/g;
	print $template;
	exit;
	}

}




sub wrong_ps
{

$error_messages1 = &ppc_settings;
$error_t  = $error_messages1->{error7};

print "Content-type: text/html\n\n";
my ($message) = @_;
if ($message eq "") {$message = "&nbsp;"};
$template = get_file_contents("$data_dir/ppc_user_login.html");
$ppc_url = qq[$script_url/ppc_login.cgi];
$pass_link = qq[$script_url/ppc_login.cgi?fct=forgot];
$username = qq[<input type="text" name="username" size="20">];
$password  = qq[<input type="password" name="password" size="20">];
$template =~ s/!!ppc_url!!/$ppc_url/g;
$template =~ s/!!username!!/$username/g;
$template =~ s/!!password!!/$password/g;
$template =~ s/!!error_message!!/$error_t/g;
$template =~ s/!!forgot_pass_link!!/$pass_link/g;
$template =~ s/!!web_url!!/$web_url/g;
print $template;

exit;
}






sub do_login
{
	my ($form_username, $form_password, $userid) = @_;
	my ($query, $thecookie1, $thecookie2, $scripts_admin);
	$query = new CGI;
	$thecookie1 = $query->cookie(	-name=>'nuser1',
			    				-value=>$form_username,
			    				-expires=>'+24h',
			    				-path=>'/');
	$thecookie2 = $query->cookie(	-name=>'npass1',
			    				-value=>$form_password,
	    						-expires=>'+24h',
	    						-path=>'/');
	$thecookie3 = $query->cookie(	-name=>'userid1',
			    				-value=>$userid,
	    						-expires=>'+24h',
	    						-path=>'/');
	print $query->header(-cookie=>[$thecookie1, $thecookie2,$thecookie3]); 
	print "<html>
	<head>
	<title>Powerseek</title>
	<meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=$script_url/ppc_login.cgi\">
	</head>
	<body>
	</body>
	</html>";

	exit;
}

sub start
{
	#print "Content-type: text/html\n\n";
	my ($message) = @_;
	if ($message eq "") {$message = "&nbsp;"};
	$template = get_file_contents("$data_dir/ppc_user_login.html");
	$ppc_url = qq[$script_url/ppc_login.cgi];
	$pass_link = qq[$script_url/ppc_login.cgi?fct=forgot];
	$username123 = qq[<input type="text" name="username" size="20">];
	$password123  = qq[<input type="password" name="password" size="20">];
	$template =~ s/!!ppc_url!!/$ppc_url/g;
	$template =~ s/!!username!!/$username123/g;
	$template =~ s/!!password!!/$password123/g;
	$template =~ s/!!error_message!!/$message/g;
	$template =~ s/!!forgot_pass_link!!/$pass_link/g;
	print $template;
	exit;
}








sub get_user_top
{
	my ($id) = @_;
	$internal_ppc_settings = &ppc_internal_settings;
	
	$order_processor  = $internal_ppc_settings->{order_processor};
	if (($order_processor eq "http://") or ($order_processor eq ""))
		{
		$order_processor = "$web_url/order_processor.html";
		}
	
	
	$template = get_file_contents("$data_dir/ppc_user_control_framework.html");
	$template =~ s/!!web_url!!/$web_url/g;
	$template =~ s/!!version!!/$version/g;
	$template =~ s/!!script_url!!/$script_url/g;
	$reg_link = qq[$script_url/ppc_registration.cgi?fct=edit_registration&id=$id];
	$listing_link = qq[$script_url/ppc_bids.cgi?fct=view_listing&id=$id];
	$reports_link = qq[$script_url/ppc_acc.cgi?id=$id];
	$template =~ s/!!reg_link!!/$reg_link/g;
	$template =~ s/!!listing_link!!/$listing_link/g;
	
	$template =~ s/!!make_payment_link!!/$order_processor/g;
	
	$template =~ s/!!reports_link!!/$reports_link/g;
	
	$acc_link = qq[$script_url/ppc_acc.cgi?id=$id];
	$template =~ s/!!account_link!!/$acc_link/g;

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

if ($template =~ /!!balance!!/i)
	{
		if ($mysql_hostname eq ""){$dsn = "DBI:mysql:$db_name";}else{$dsn = "DBI:mysql:$db_name:$mysql_hostname:$mysql_port";}
		$dbh = DBI->connect($dsn, $db_username, $db_password);
		if ( !defined $dbh ) {die "Cannot connect to MySQL server: $DBI::errstr\n"; }

		$sql = "SELECT balance FROM ppc_users WHERE id = '$id'";
		$sth = $dbh->prepare($sql);
		$sth->execute;
		$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
		$rows = $sth->rows();

		while ( @row = $sth->fetchrow() )
			{
			$rbalance = $row[0];
			}
		$sth->finish;
		$dbh->disconnect;
		
		$template =~ s/!!balance!!/$rbalance/g;
	}

	
	return ($template);
}






sub strip_character
{
	my ($strip_it) = @_;
	$strip_it =~ s/'/\\'/g;
	$strip_it =~ s/"\\"/g;
#	$strip_it =~ s/;//g;
	return ($strip_it);
}

#### END CONFIGURATION ########################################################

1;