#!/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 $version/;

@ISA = qw(Exporter);

@EXPORT = qw(check_access
	    		get_template
	    		encode_dir
	    		decode_dir
	    		problem_popup
	    		get_chopped_path
	    		remove_leading_spacing
	    		update_numbers
	    		get_location_string
	    		get_file_contents
	    		get_last_dirname
	    		get_rid
	    		decode_complete_dir
	    		get_extra_vars
	    		decode_date
	    		get_date_selbox
	    		get_version); 

@EXPORT_OK = qw($template1
					 $enc_string
					 $decoded_string
					 $chopped_path
					 $chopped_string
					 $locstr_ret
					 $thefile
					 $drval
					 $mcid_str
					 $decstr
					 $extrakfd
					 $rdvalue
					 $date_dbox
					 $pversion);

#$prgname = "PowerSeek Version 2.1";
$copyright = "Copyright ©2005 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 get_heading_box
{
my ($h_icon, $h_heading, $h_text, $hdr) = @_;

if ($hdr eq "header")
{
$hhead = qq[
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">	
<html>
<head>
<title>PPC Administration</title>
<link href="$web_url/ppc_ps.css" rel="stylesheet" type="text/css" />
</head>
<body>
];

$bothd = qq[
</body>
</html>
];
}


$h_return = qq[$hhead<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#E1E1E1">
 <tr>
  <td width="1%" valign="top" bgcolor="#FFFFFF"><img src="$h_icon"></td>
  <td width="99%" valign="top" bgcolor="#FFFFFF"><table width="100%" border="0" cellpadding="6">
 <tr>
  <td background="$web_url/ppc_bar3.gif" class="normaltext12"><strong>$h_heading</strong></td>
 </tr>
 <tr>
  <td class="normaltext12">$h_text</td>
 </tr>
</table></td></tr></table>
<table border="0" cellpadding="0" cellspacing="0" width="100%" background="$web_url/shadow.gif">
  <tr>
  <td width="1%" bgcolor="#FFFFFF" height="14"></td><td width="99%"></td>
  </tr>
</table>$bothd];

return ($h_return);
}



sub demo
{

print qq[<html>

<head>
<title>PowerSeek</title>
</head>

<body>

<p align="center"><img src="http://www.focalmedia.org/ppc/psdemo.jpg"></p>
<div align="center"><center>

<table border="0" cellpadding="10" cellspacing="0" width="80%"
style="border: 1px solid rgb(225,225,225)">
  <tr>
    <td width="100%"><span style="line-height: 20px"><font face="Arial" size="2">Some features
    of the this Control Panel Demo has been disabled to protect the contents of this Demo so
    that we can present it to you in an orderly fashion. Some functions has also been disabled
    to protect the security of our server.<br>
    <br>
    <b>Use the back button of your browser to go back</b></font></span></td>
  </tr>
</table>
</center></div>

<p><br>
</p>
</body>
</html>

];
exit;




}



sub get_version
{
$pversion = "PowerSeek PPC Plugin Version 1.3";
return ($pversion);
}


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"; }
if ($Sstart_year eq "2018") { $start_year[15] = "selected"; }
if ($Sstart_year eq "2019") { $start_year[16] = "selected"; }
if ($Sstart_year eq "2020") { $start_year[17] = "selected"; }
if ($Sstart_year eq "2021") { $start_year[18] = "selected"; }
if ($Sstart_year eq "2022") { $start_year[19] = "selected"; }
if ($Sstart_year eq "2023") { $start_year[20] = "selected"; }
if ($Sstart_year eq "2024") { $start_year[21] = "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[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>
		<option $start_year[15] value="2018">2018</option>
		<option $start_year[16] value="2019">2019</option>
		<option $start_year[17] value="2020">2020</option>
		<option $start_year[18] value="2021">2021</option>
		<option $start_year[19] value="2022">2022</option>
		<option $start_year[20] value="2023">2023</option>
		<option $start_year[21] value="2024">2024</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 "===>In the beginning PPC ST was: $ppc_st<br>";
	my ($search_results,$count);
	@cus_details = "";
	$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;
	$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";}
	#print "==> Query 1 is: $sql<br>";
	$sql1 = "select * from ppc_keywords where (keywords = '$key_phrase' or keywords like '%$key_phrase%')";
	while ($my_user = $sth->fetchrow())
	{
		$sql1 .= " and user_id != '$my_user'";
	}
	$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";}
	#print "==> Query 3 is: $sql1<br>";
	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);
		}
		&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]" 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";}
}





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;
	$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 ($my_code ne "Return")
	{
		$temp_filename = "click_" . $ENV{"REMOTE_ADDR"} . ".dat";
		#open (KOOS , "> $data_dir/koos123.dat");
		$value = $query->cookie('PPC_click');
		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);
		}
		#print KOOS "$value = `cat $sourcedir/$temp_filename`;\n";
		#print KOOS "value is:$value\n";
		#print KOOS "if ((-e \"$sourcedir/$temp_filename\") == 1)\n";
		$compare_link = "a" . $link_id . "a";
	#	$value = "";
		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;
		}
		if ($value =~ /$compare_link/i)
		{
			$return_detail[1] = $link_detail[1];
			return(@return_detail);
		}
		else
		{
			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
			{
				$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'";
				$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)
			{
				$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]);
	}
#	close(KOOS);
}


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
{
	print "==>Doing SearchFeed<br>";
	my ($keywords, $number, $track_id,  $account_id, $searchfeed_numresults, $skip_number, $diff)  = @_;
	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;
	} 
		$pass_string = "http://www.searchfeed.com/rd/feed/TextFeed.jsp?trackID=$track_id&pID=$account_id&cat=$keywords&nl=$searchfeed_numresults&page=$diff&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
{
#	print "Content-type: text/html\n\n";
	my ($EnteredUser, $EnteredPass) = @_;
	my ($usercookie, $passcookie, $query);
#	print "==>Checking Access<br>";
	if ($q->param('fct') eq "forgot") {&forgot;}
	elsif ($q->param('fct') eq "mailpass") {&mailpass;}
	elsif ($q->param('fct') eq "wait_active") {&wait_active;}
	elsif ($q->param('fct') eq "loginnow") {&loginnow;}
	&dbconnect;
	if (($EnteredUser eq "") and ($EnteredPass eq ""))
	{
#		print "==>EnteredUser and EnteredPass Empty<br>";
		$query = new CGI;
		$usercookie = $query->cookie('nuser1');
		$passcookie = $query->cookie('npass1');
		$id = $query->cookie('userid1');
		$sql = "select username, password, id from ppc_users where username = '$usercookie' ";
#		print "==>SQL is: $sql, select username, password, id from ppc_users where username = usercookie <br>";
	}
	elsif ($EnteredUser ne "")
	{
#		print "==>EnteredUser Not Empty<br>";
		$sql = "select username, password, id from ppc_users where username = '$EnteredUser' ";
#		print "==>SQL is: $sql, select username, password, id from ppc_users where username = EnteredUser <br>";
	}
	$sth = $dbh->prepare($sql);
	$sth->execute;
	$serror = ""; $serror = $sth->errstr; if ($serror ne "") {die "SQL Syntax Error: $serror \n From: $sql";}
	@my_user = $sth->fetchrow();
	$DatabaseUsername = $my_user[0];
	$DatabasePassword = $my_user[1];
	$id = $my_user[2];
	$error7 = $error_messages->{error7};
	$support_email  = $ppc_features->{support_email};
	$error7 =~ s/%%support_email%%/<a href=\"mailto:$support_email\">$support_email<\/a>/g;
	if (($EnteredUser ne "") and ($EnteredPass ne "")) 
	{
#		print "==>EnteredUser and EnteredPass Not Empty<br>";
		if (($EnteredUser ne $DatabaseUsername) and ($EnteredPass ne $DatabasePassword)) 
		{
#			print "==>EnteredUser ne DatabaseUsername and EnteredPass ne DatabasePassword<br>";
			&start($error7);
		}
		else
		{
#			print "==>ELSE EnteredUser ne DatabaseUsername and EnteredPass ne DatabasePassword<br>";
			&do_login($EnteredUser,$EnteredPass, $id);
		}
	}
	if (($usercookie eq "") and ($passcookie eq "")){&start;}
	if (($usercookie ne $DatabaseUsername) or ($passcookie ne $DatabasePassword)){&start($error7);}
#	print "==>Finish Checking<br>";
}

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_template
{

my ($menu) = @_;

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

$shortcuts = <<END_OF_SHC;
<table width="100%" border="0" cellspacing="1" cellpadding="6">
  <tr>
    <td>

<form method="POST" action="$admin_url/ppc_user_admin.cgi" name="searchform" target="_blank" style="margin-bottom:0; margin-top:0;">
  <input type="hidden" name="fct" value="searchby">
  <input type="hidden" name="search_field" value="16">
  <span class="whitetext_ta"><strong>Find PPC User:
  </strong><br>(User Account Search)</span><br>
  <input type="text" name="search_string" size="11"> <input type="submit" class="psbutton" value="Go"
  name="B1" onClick="submitsearch(document.searchform); return false;">
</form>

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="20" valign="bottom"></td>
  </tr>
</table>

<form method="POST" action="$admin_url/ppc_links.cgi" name="searchform" target="_blank" style="margin-bottom:0; margin-top:0;">
  <input type="hidden" name="fct" value="get_data"><input type="hidden" name="left_bar"
  value="10"><span class="whitetext_ta"><strong>Search PPC Links:</strong><br>
  (Find PPC Links)</span><br>
  <input type="text" name="keywords" size="11"> <input type="submit" class="psbutton" value="Go"
  name="B3">
</form>

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="20" valign="bottom"></td>
  </tr>
</table>

<form method="POST" action="$script_url/search2.cgi" target="_blank" style="margin-bottom:0; margin-top:0;" >
  <span class="whitetext_ta"><strong>PowerSeek Search:</strong><br>
  (End User Search)</span><br>
  <input type="text" name="keywords" size="11"> <input type="submit" class="psbutton" value="Go" name="B1">
</form></td>
  </tr>
</table>

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td height="140" valign="bottom">
    <a href="$admin_url/admin.cgi"><img src="$web_url/ppc_switch2.gif" border="0"></a>
	 <a href="$admin_url/ppc_integrate.cgi"  target="_blank"><img src="$web_url/ppc_int.gif" border="0"></a>
    </td>
  </tr>
</table>


END_OF_SHC

#onClick="submitsearch(document.searchform); return false;"
##############

$butt[0] = qq[<a href="$admin_url/p_internal_ppc.cgi" id="homebut"><span>Home</span></a>];
$butt[1] = qq[<a href="$admin_url/ppc_setting.cgi" id="ppc_asettings"><span>Settings</span></a>];
$butt[2] = qq[<a href="$admin_url/ppc_user_admin.cgi" id="ppc_userm"><span>User Manager</span></a>];
$butt[3] = qq[<a href="$admin_url/ppc_payments.cgi" id="ppc_apay"><span>Payments</span></a>];
$butt[4] = qq[<a href="$admin_url/ppc_links.cgi" id="ppc_alink"><span>Link Manager</span></a>];
$butt[5] = qq[<a href="$admin_url/ppc_template.cgi" id="ppc_atmpl"><span>Template Manager</span></a>];
$butt[6] = qq[<a href="$admin_url/ppc_reports2.cgi" id="ppc_arep"><span>Reports</span></a>];
$butt[7] = qq[<a href="$admin_url/ppc_backup.cgi" id="ppc_autil"><span>Utilities</span></a>];

#$butt[0] = "<a href=\"$admin_url/ppc_setting.cgi\"><img src=\"$web_url/ppc_verify.gif\" border=\"0\">";
#ppc_payments.cgi ppc_payments.gif
#ppc_banip.gif ppc_ban_ip.cgi

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




if ($menu eq "PPC_HOME")
	{
	$butt[0] = qq[<a href="$admin_url/p_internal_ppc.cgi"><img src="$web_url/ppc_ahome1.gif" border="0"></a>];
	}
	elsif ($menu eq "SETTINGS")
	{
	$butt[1] = qq[<a href="$admin_url/ppc_setting.cgi"><img src="$web_url/ppc_asettings1.gif" border="0"></a>];
	}
	elsif ($menu eq "USERMAN")
	{
	$butt[2] = qq[<a href="$admin_url/ppc_user_admin.cgi"><img src="$web_url/ppc_userm1.gif" border="0"></a>];
	}	
	elsif ($menu eq "PAYMENTS")
	{
	$butt[3] = qq[<a href="$admin_url/ppc_backup.cgi"><img src="$web_url/ppc_apay1.gif" border="0"></a>];
	}
	elsif ($menu eq "LNKMAN")
	{
	$butt[4] = qq[<a href="$admin_url/ppc_reports2.cgi"><img src="$web_url/ppc_alink1.gif" border="0"></a>];
	$b_home = "ppc_home2.gif";
	}
	elsif ($menu eq "TEMPLATES")
	{
	$butt[5] = qq[<a href="$admin_url/ppc_payments.cgi"><img src="$web_url/ppc_atmpl1.gif" border="0"></a>];
	}
	elsif ($menu eq "REPORTS")
	{
	$butt[6] = qq[<a href="$admin_url/ppc_links.cgi"><img src="$web_url/ppc_arep1.gif" border="0"></a>];
	}
	elsif ($menu eq "UTILS")
	{
	$butt[7] = qq[<a href="$admin_url/ppc_template.cgi"><img src="$web_url/ppc_autil1.gif" border="0"></a>];
	}

#$buttons = $butt[0] . $butt[1]. $butt[2] . $butt[7] . $butt[6] . $butt[3] . $butt[4] . $butt[5];

$buttons = qq[
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="1%">$butt[0]</td>
    <td width="1%">$butt[1]</td>
    <td width="1%">$butt[2]</td>
    <td width="1%">$butt[3]</td>
    <td width="1%">$butt[4]</td>
    <td width="1%">$butt[5]</td>
	 <td width="1%">$butt[6]</td>    
	 <td width="1%">$butt[7]</td>    
    <td width="92%"></td>
  </tr>
</table>
];

########

#$cpanel = &get_file_contents("$data_dir/ppc_control_panel.html");

$cpanel = qq[

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">	
<html>
<head>
<title>PPC Administration</title>
<link href="$web_url/ppc_ps.css" rel="stylesheet" type="text/css" />

<style>
 
#homebut { display: block; width: 53px; height: 22px; background: url("$web_url/ppc_ahome.gif") no-repeat 0 0; }
#homebut:hover { background-position: 0 -22px; }
#homebut span {display: none; }

#ppc_asettings { display: block; width: 68px; height: 22px; background: url("$web_url/ppc_asettings.gif") no-repeat 0 0; }
#ppc_asettings:hover { background-position: 0 -22px; }
#ppc_asettings span {display: none; }

#ppc_userm { display: block; width: 104px; height: 22px; background: url("$web_url/ppc_userm.gif") no-repeat 0 0; }
#ppc_userm:hover { background-position: 0 -22px; }
#ppc_userm span {display: none; }

#ppc_apay { display: block; width: 78px; height: 22px; background: url("$web_url/ppc_apay.gif") no-repeat 0 0; }
#ppc_apay:hover { background-position: 0 -22px; }
#ppc_apay span {display: none; }

#ppc_alink { display: block; width: 78px; height: 22px; background: url("$web_url/ppc_alink.gif") no-repeat 0 0; }
#ppc_alink:hover { background-position: 0 -22px; }
#ppc_alink span {display: none; }

#ppc_atmpl { display: block; width: 113px; height: 22px; background: url("$web_url/ppc_atmpl.gif") no-repeat 0 0; }
#ppc_atmpl:hover { background-position: 0 -22px; }
#ppc_atmpl span {display: none; }

#ppc_arep { display: block; width: 64px; height: 22px; background: url("$web_url/ppc_arep.gif") no-repeat 0 0; }
#ppc_arep:hover { background-position: 0 -22px; }
#ppc_arep span {display: none; }

#ppc_autil { display: block; width: 64px; height: 22px; background: url("$web_url/ppc_autil.gif") no-repeat 0 0; }
#ppc_autil:hover { background-position: 0 -22px; }
#ppc_autil span {display: none; }

</style>


<script LANGUAGE="JavaScript">

  function popup(loc,ww,hh)
   {
    var mywidth = (ww + 0);
    var myheight = (hh + 0);
    var myspecs = "'menubar=0,status=1,resizable=1,location=0,titlebar=1,toolbar=1,scrollbars=1,width=" + mywidth + ",height=" + myheight + "'";
	var random = parseInt(Math.random()*10000)

	  var popupwin = null;
      myWindow = open (loc, popupwin + random, myspecs);
      myWindow.moveTo(100,40);
      myWindow.focus();

    }

 function submitsearch(theForm)
   {
     var windowName = "Saerch";
     windowURL = theForm.action + '?';
     windowURL = windowURL + "keywords=" + theForm.keywords.value;
     var myspecs = "'menubar=0,status=1,resizable=1,location=0,titlebar=1,toolbar=1,scrollbars=1,width=600,height=400'";

     var popupwin = null;
     myWindow = open(windowURL, popupwin, myspecs);
     myWindow.focus();
   }

 </script>
 
</head>

<body topmargin="0" leftmargin="0">




<table border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#01019F">
  <tr>
    <td width="64%" height="100" valign="bottom" class="ppctop"><table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td width="1%" valign="bottom"><img src="$web_url/ppc_rvb.gif" width="153" height="1"></td>
        <td width="99%">!!pmenu!!</td>
      </tr>
    </table></td>
<td width="36%" align="center" bgcolor="#01019F"><strong><a href="http://www.focalmedia.net/ppc_manual/"> <img src="$web_url/manual.gif" border="0"> </a> </strong> <a href="http://www.focalmedia.net/cgi-bin/psmembers/members.cgi"> <img src="$web_url/support2.gif" border="0"> </a> <br>
        <span class="whitetext">Copyright !!year!! FocalMedia.Net <strong> <br>
    !!version!!</strong></span></td>
  </tr>
</table>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="1%" valign="top"><img src="$web_url/ppc_stl.gif" width="156" height="12"></td>
    <td width="99%" valign="bottom" background="$web_url/ppc_st2l.gif"></td>
  </tr>
  <tr>
    <td valign="top" class="ppcleft"><BR>$shortcuts</td>
    <td valign="top">!!data!!</td>
  </tr>
</table>


</body>
</html>

];


if ((-e "$fplug") < 1) 
	{
	$cpanel =~ s/$uplug2/$uplug/i;
	}

########

$cpanel =~ s/!!web_url!!/$web_url/gi;
$cpanel =~ s/!!admin_url!!/$admin_url/gi;



$version = &get_version;
$cpanel =~ s/!!version!!/$version/gi;



$thetime = time();
($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime($thetime);
$year = "20" . substr($year, 1, 2);

$cpanel =~ s/!!year!!/$year/gi;

$cpanel =~ s/!!subt!!/$subt/gi;
$cpanel =~ s/!!pmenu!!/$buttons/g;

return ($cpanel);

}


sub get_user_top
{
	my ($id) = @_;
	$internal_ppc_settings = &ppc_internal_settings;
	$order_processor  = $internal_ppc_settings->{order_processor};
	$template = get_file_contents("$data_dir/ppc_user_control_framework.html");
	$template =~ s/!!web_url!!/$web_url/g;
	
	$version = &get_version;
	$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_reports.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;
	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;