<?php

/* NOTE: 	If you are seeing the text of this page when browsing to this script in your web browser
*				it most likely means that you need to ask your web host to add/change the following
*				Apache option in the apache configuration file:
*				
*				 AllowOverride FileInfo
*/

$sAuthKey='c9928fcdee0df64bb1378fb64600a999';
$iSubscriptionId='671';
$sDatafeedType='default';
$sServer1='ws2.avantlink.com';
$sServer2='ws3.avantlink.com';
$sServer3='ws1.avantlink.com';
$sServer4='ws4.avantlink.com';
$sServer5='ws5.avantlink.com';

/*
* Setup all the local page variables
*/
$aURL = parseURL();
$sDataType = $aURL['sDataType'];
$sDataValue = intval($aURL['sDataValue']);
$iDisplayBase = intval($aURL['iDisplayBase']);
$sPageName = $aURL['sPageName'];
$sCachePath = $aURL['sCachePath'];
$sAvantFilePath = $aURL['sAvantFilePath'];
ini_set("include_path", $aURL['sAvantIncludePath']);

// Set the full url address
$sWebRoot = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];

// Set some web tracking variables
$sIP = $_SERVER['REMOTE_ADDR'];
$sRef = $_SERVER['HTTP_REFERER'];
if (trim($sRef) == '') {
	$sRef = $_SERVER['PHP_SELF'];
}

// Check for cache clear parameters
if (isset($_GET['cca'])) {
	$cache_clear_auth = $_GET['cca'];
	$bDoCacheClean = intval($_GET['bdcc']);
}

switch ($sDataType)
{
	case 'D' :
		$iPageIdType = 0;
		break;
		
	case 'C' :
		$iPageIdType = 1;
		break;
		
	case 'S' :
		$iPageIdType = 2;
		break;
	
	case 'P' :
		$iPageIdType = 3;
		break;
		
	case 'SEARCH' :
		$iPageIdType = 4;
		$sDataValue = $_GET('st');
		echo "<p>Data Value: $sDataValue</p>";
		$sDataValue = urldecode($_GET['st']);
		break;
		
	case 'FORM'	:
		$iPageIdType = 5;
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') { $sDataValue = parseFormIntoXML($_POST); }
		else { $sDataValue = $_GET['ft']; }
		break;	
	
	case 'CLICK' :
		//$strProductLink = "http://ws1.avantlink.com/track/buy.php?p=$this->_iPubDatafeedAssocId&pt=3&pi=$iProductId&ip=$this->_sPageHitIP&ref=$this->_sPageHitReferrer";
		$sClickServer = strip_tags(urldecode($_GET['srv']));
		$iProductId = intval($_GET['pri']);
		$sLink = $sClickServer . '?p=' . $iSubscriptionId . '&pt=3&pi=' . $iProductId . '&ip=' . $sIP . '&ref=' . $sRef;
		header("Location: $sLink");
		break;	
		
	default :
		$iPageIdType = 0;
}

$bDoCache = true;

/*
* Check to make sure cache directory is writeable
*/
if (!is_writable($sCachePath)) {
	echo '<p style="background: #ff3939; font-weight: 600; color: yellow;">WARNING: The cache directory located at ' . $sCachePath . ' needs to have the permissions set to read/write/execute for everyone in order to work properly.<br/><a href="http://www.dynamicwebsource.com/docs/cache_permissions.php" target="_blank">Click here for instructions.</a></p>';
}

/*
* Check to make sure the include path is where it should be
*/
if (!is_dir($aURL['sAvantIncludePath'])) {
	echo '<div style="background: #ff3939; font-weight: 600; color: yellow;">WARNING: <br/><blockquote>The avant_include directory should be located at ' . $aURL['strAvantIncludePath'] . '<br/>Please make sure the directory is uploaded to this location.</blockquote></div>';
}

/*
* Check to make sure the fopen function is allowed
*/
$fopen_allowed = (bool) ini_get('allow_url_fopen');
if (!$fopen_allowed) {
	echo '<div style="background: #ff3939; font-weight: 600; color: yellow;">WARNING: <br/><blockquote>It appears the your host is not allowing the php fopen function. This functionality is mandatory to communicate with our datafeed server. Please contact your hosting company technical support and tell them you need the php fopen functionality turned on for your account.</blockquote></div>';
}

// Set cache options
$aOptions = array	(
						'cacheDir' => $sCachePath,
						'lifeTime'	=> 86400,
						'automaticCleaningFactor' => 50,
						'hashedDirectoryLevel' => 4
					);

require_once('Cache/Lite.php');

// Create a Cache_Lite object 
$Cache_Lite = new Cache_Lite($aOptions);

/*
* Clear the cache if valid authorization was passed
*/
if ($sAuthKey == $cache_clear_auth) {
	if ($bDoCacheClean) {
		$Cache_Lite->clean();
	}
}

// Test if there is a valid cache-entry for this key 
if (($oData = $Cache_Lite->get($sPageName . $sDataType . $sDataValue . $iDisplayBase)) && ($sDataType != 'FORM')) {
   echo $oData;
} 
else {
	// Get additional required scripts  
	require_once ('SOAP/Client.php');
	require_once ("$sAvantFilePath/WebService_DatafeedManager.php");
	require_once ('Net/Portscan.php');
	
	
	if (Net_Portscan::checkPort($sServer1, 80, 5) == NET_PORTSCAN_SERVICE_FOUND) {
		$sWebServiceURL = $sServer1;
	}
	elseif (Net_Portscan::checkPort($sServer2, 80, 5) == NET_PORTSCAN_SERVICE_FOUND) {
		$sWebServiceURL = $sServer2;
	}
	elseif (Net_Portscan::checkPort($sServer3, 80, 5) == NET_PORTSCAN_SERVICE_FOUND) {
		$sWebServiceURL = $sServer3;
	}
	elseif (Net_Portscan::checkPort($sServer4, 80, 5) == NET_PORTSCAN_SERVICE_FOUND) {
		$sWebServiceURL = $sServer4;
	}
	else {
		$sWebServiceURL = $sServer5;
	}
	
	
	$oClient = new WebService_DatafeedManager($sWebServiceURL);
	$oClient->setOpt('timeout', 30);
	$oReturn = $oClient->getFeedData(	$sAuthKey, 
										$iSubscriptionId, 
										$sDatafeedType, 
										$sWebRoot, 
										$sDataType,
										$sDataValue,
										$iDisplayBase,
										$sIP,
										$sRef
									);
	
	if (PEAR::isError($oReturn))
	{
		echo '<p>Error: ' . $oReturn->getMessage();	
		$bDoCache = false;
	}
	else
	{	
		$page_title = $oReturn->sPageTitle;
		$page_keywords = $oReturn->sPageKeywords;
		$page_description = $oReturn->sPageDescription;
		$page_navigation = $oReturn->sPageNavigation;
		$page_content = $oReturn->sPageBody;
		$hit_tracking = "<script type=\"text/javascript\" src=\"http://$sWebServiceURL/track/pageHit.php?a=$sAuthKey&p=$iSubscriptionId&pt=$iPageIdType&pi=$sDataValue&ip=$sIP&ref=$sRef\"></script>";
	}
	
	/**
	* Get the page template
	*/
	if (is_file($sAvantFilePath . "/template.php")) {
		require_once($sAvantFilePath . "/template.php");
	}
	elseif (is_file($sAvantFilePath . "/template.html")) {
		$filename = $sAvantFilePath . "/template.html";
		$handle = fopen($filename, "r");
		$strHTML = fread($handle, filesize($filename));
		fclose($handle);
		
		$strHTML = eregi_replace('\[PAGE_TITLE\]', $page_title, $strHTML);
		$strHTML = eregi_replace('\[PAGE_KEYWORDS\]', $page_keywords, $strHTML);
		$strHTML = eregi_replace('\[PAGE_DESCRIPTION\]', $page_description, $strHTML);
		$strHTML = eregi_replace('\[PAGE_NAVIGATION\]', $page_navigation, $strHTML);
		$strHTML = eregi_replace('\[PAGE_CONTENT\]', $page_content, $strHTML);
		$strHTML = eregi_replace('\[HIT_TRACKING\]', $hit_tracking, $strHTML);
		
		echo $strHTML;
	}
	else {
		echo "Error: No template file was found. Please make sure a template.html file is located in the same directory as this script.";
		exit();
	}
	
	if ($bDoCache) {
		$Cache_Lite->save($strHTML);
	}
}

/** 
* This function splits parameters out of a search engine friendly url
*/
function parseURL()
{
	// Parse out the URL parameters
	$sURL = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
	$aURL = explode('/', $sURL);
	
	array_shift($aURL);
	$aTemp = explode('-', $aURL[0]);
	
	// Parse out and set file path info
	$aScriptName = explode('/', $_SERVER['SCRIPT_NAME']);
	$sScriptName = array_pop($aScriptName);
	$sFilePath = $_SERVER['DOCUMENT_ROOT'] . implode('/', $aScriptName);
	$sWebPath = 'http://' . $_SERVER['SERVER_NAME'] . implode('/', $aScriptName);
	$sCachePath = $sFilePath . '/cache/';
	
	$sServiceFolder = array_pop($aScriptName);
	$sIncludePath = $_SERVER['DOCUMENT_ROOT'] . implode('/', $aScriptName) . '/avant_includes/';
	
	$aParams = array	(	'sDataType'			=> $aTemp[0],
							'sDataValue'		=> $aTemp[1],
							'iDisplayBase'		=> intval($aTemp[2]),
							'sPageName'			=> $aURL[1],
							'sAvantFilePath'	=> $sFilePath,
							'sAvantWebPath'		=> $sWebPath,
							'sAvantIncludePath'	=> $sIncludePath,
							'sCachePath'		=> $sCachePath
						);
	return $aParams;
}

function parseFormIntoXML($aData)
{
	$sXML = "<xml>\n";
	
	foreach ($aData as $key => $value)
	{
		$sXML .= "<$key>" . $value . "</$key>\n";
	}
	
	$sXML .= "</xml>\n";
	
	return $sXML;
}

?>
