<? include "../connect.php" ?>

<?

set_time_limit(0);

$jse_global_flagas;
$jse_global_objectid;
$jse_global_action;
$jse_global_hostname	= $MySqlHostname;
$jse_global_uname		= $MySqlUsername;
$jse_global_pword		= $MySqlPassword;
$jse_global_db			= $MySqlDatabase;
$jse_global_dblink		= $dblink;

// Fetch the e-mail
$options = mysql_query("select * from jse_settings where id='1'")
	or die( "Couldn't fetch e-mail address somehow" );
$array = mysql_fetch_array($options);
$jse_global_to = $array["amail"];
$jse_global_exchangename = $array["exchangename"];

function resetConnection()
{
	// Close the Connection
	mysql_close($GLOBALS['jse_global_dblink']);	
	
	//Restart the Connection
	$GLOBALS['jse_global_dblink'] = MYSQL_CONNECT($GLOBALS['jse_global_hostname'], $GLOBALS['jse_global_uname'], $GLOBALS['jse_global_pword']) or die("Could not connect to database");
	@mysql_select_db("".$GLOBALS['jse_global_db']."") or die( "Could not select database");
}

function mail_user($subjectid, $id)
{
	// E-mail about the cleanup starting
	if( $subjectid == 'scriptstart' )
	{
			$subject = "Cleanup Script: Starting Cleanup for ".$GLOBALS['jse_global_exchangename']."!";
$body = "Dear Admin,

The Cleanup Script has started checking all banners and traffic links in the database for errors on ".$GLOBALS['jse_global_exchangename'].". This procedure can take anywhere from an hour up to 6 hours depending on how big your database is.

Nothing will be affected while this operation is being performed and nothing has to be done by you, the Admin. This script will handle everything. But as this script can take a while to finish, please wait until you receive another e-mail from the Cleanup Script saying  'The cleanup is Done' before you start removing broken Banners and Traffic Links.
-The Cleanup Script";
			mail($GLOBALS['jse_global_to'], $subject, $body);
	}
	
	// E-mail about the cleanup ending
	if( $subjectid == 'scriptend' )
	{
			$subject = "Cleanup Script: Cleanup has finished for ".$GLOBALS['jse_global_exchangename']."!";
$body = "Dear Admin,

The Cleanup Script has finished the checking of broken Banners and Links on ".$GLOBALS['jse_global_exchangename']."! You can now enter the 'View Broken Banners' and the 'View Broken Traffic Links' pages to see the list of broken and or suspicious Banners/Traffic Links.
Good luck and see you next time!

-The Cleanup Script";
			mail($GLOBALS['jse_global_to'], $subject, $body);
	}
	
	// We received a dangerous url, e-mail the admin about it
	if( $subjectid == 'dangerousurl' )
	{
			if( $GLOBALS['jse_global_action'] == 'banner' )
			{
				$subject = "Cleanup Script: Dangerous URL detected in a Banner at ".$GLOBALS['jse_global_exchangename']."!";
$body = "Dear Admin,

A Banner with a dangerous URL was detected on ".$GLOBALS['jse_global_exchangename'].". This URL could've exploited the script and executed custom code and therefor has been stopped. The ID of the Banner is: $id.
Please log in to your PHPMyAdmin to fix or delete the Banner.<br><br>-The Cleanup Script";
			}
			else if( $GLOBALS['jse_global_action'] == 'tlinks' )
			{
				$subject = "Cleanup Script: Dangerous URL detected in a Traffic Link!";
$body = "Dear Admin,

A Traffic Link with a dangerous URL was detected. This URL could've exploited the script and executed custom code and therefor has been stopped. The ID of the Banner is: $id.
Please log in to your PHPMyAdmin to fix or delete the Traffic Link.

-The Cleanup Script";
			}
			mail($GLOBALS['jse_global_to'], $subject, $body);
	}
}

function is_valid_url ( $url )
{	
		if( preg_match('/\bhttps\b/i', $url) )
		{
			return true;
		}
		if( preg_match('/\bhttps\b/i', $url) )
		{
			return true;
		}
		
		if( preg_match('/\bhref=\b/i', $url) )
		{
			warning_mail_user("dangerousurl", $GLOBALS['jse_global_objectid']);
			$url = '';
			return true;
		}
		
		$url = @parse_url($url);
		
		if ( ! $url) {
			return true;
		}
			
		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';
	
		if ($path == '')
		{
			$path = '/';
		}
		
		$path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';
		
		if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) )
		{
			if ( PHP_VERSION >= 5 )
			{
				$headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
				
					if( $headers == '' )
					{
						return true;
					}
					else if( preg_match('/\b404\b/i', $headers[0]) )
					{
						$GLOBALS['jse_global_flagas'] = 404;
						return false;
					}
					else if( preg_match('/\b301\b/i', $headers[0]) )
					{
						$GLOBALS['jse_global_flagas'] = 301;
						return true;
					}
					else if( preg_match('/\b302\b/i', $headers[0]) )
					{
						$GLOBALS['jse_global_flagas'] = 301;
						return true;
					}
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 100);

				if ( ! $fp )
				{
					return true;
				}
				fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
				$headers = fread ( $fp, 128 );
				fclose ( $fp );
			}
			$headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
			return true;
		}
	return true;
}











	/*************************/
	/*** Check the Banners ***/
	/*************************/
	mail_user('scriptstart', 0);
	$data = "select * from banners where status='1'"; //limit 0,30
		$result = mysql_query( $data )
			or die( "Query Failed " );
	$num_rows = mysql_num_rows( $result );

		$row = 1;
		
		
	while( $line = mysql_fetch_array( $result ) )
	{
		resetConnection();
	
		
		$bannerurl 	= $line['bannerurl'];
		$targeturl	= $line['targeturl'];
		$postedby	= $line['userid'];
		$bannerid	= $line['id'];
		$GLOBALS['jse_global_objectid'] = $bannerid;
		$GLOBALS['jse_global_action'] = 'banners';
		
		$targeturlflag = 0;
		$bannerurlflag = 0;
		$jse_today = date( 'Y-m-d',strtotime( "now" ) );
		$flag = 0;
		
		
		// Check the Banner URL
		if( !is_valid_url( $bannerurl ) )
		{
			$flag = 1;
			$bannerurlflag = 1;
			
			$bannerurlflagtype = $GLOBALS['jse_global_flagas'];
		}
		// Check the TARGET URL
		if( !is_valid_url( $targeturl ) )
		{
			$flag = 1;
			$targeturlflag = 1;
			
			$targeturlflagtype = $GLOBALS['jse_global_flagas'];
		}
		
		if( $flag == 1) // This is active right now
		{
			$query2 = "INSERT INTO `jse_bannerlist` (`bannerid`, `targeturl`, `bannerurl`, `targeturlflag`, `bannerurlflag`, `bannerurlflagtype`, `targeturlflagtype`, `flagdate`, `postedby`) VALUES ('".$bannerid."', '".$targeturl."', '".$bannerurl."', '".$targeturlflag."', '".$bannerurlflag."', '".$targeturlflagtype."', '".$bannerurlflagtype."', '".$jse_today."', '".$postedby."')";
				$result2 = mysql_query( $query2 )
			or die( mysql_error() );
		}
		else
		{
			
		}
		
		if( mysql_error() )
		{
			$print = mysql_error();
			echo( "<br><br><b><font color='red'>An error occured: $print</font></b><br><br>" );
		}
		$row++;
	}
	
	/*******************************/
	/*** Check the Traffic Links ***/
	/*******************************/
	
	$data = "select * from tlinks where approved='1'"; //limit 0,30
		$result = mysql_query( $data )
			or die( "Query Failed " );
	$num_rows = mysql_num_rows( $result );
		
		$row = 1;
		
	while( $line = mysql_fetch_array( $result ) )
	{
		resetConnection();
		
		
		$id		 	= $line['id'];
		$userid		= $line['userid'];
		$subject	= $line['subject'];
		$url		= $line['url'];
		$GLOBALS['jse_global_objectid'] = $id;
		$GLOBALS['jse_global_action'] = 'tlinks';
		
		$jse_today = date( 'Y-m-d',strtotime( "now" ) );
		$flag = 0;
		
		
		// Check the URL
		if( !is_valid_url( $url ) )
		{
			$flag = 1;
			$flagtype = $jse_global_flagas;
			
		}
		
		// If errors were encountered, store it into the Database
		if( $flag == 1 )
		{
			$subject = mysql_real_escape_string($subject);
			$query2 = "INSERT INTO `jse_trafficlinklist` (`tlinkid`, `userid`, `subject`, `url`, `flagtype`, `flagdate`) VALUES ($id, '".$userid."', '".$subject."', '".$url."', '".$flagtype."', '".$jse_today."')";
				$result2 = mysql_query( $query2 )
					or die( "Query Failed<br><br>Error:<br>$id<br>$userid<br>$subject<br>$url<br><br>" );
					
		}
		else
		{
			
		}
		
		if( mysql_error() )
		{
			$print = mysql_error();
			echo( "<br><br><b><font color='red'>An error occured: $print</font></b><br><br>" );
		}
		$row++;
	}
	
	mail_user('scriptend', 0);
?>