<?php
 $DebugIPs = array('66.194.84.4');
//echo "OK"; exit();
//	error_log(var_dump($_SERVER), 1, 'brian@macserve.net');

$hitTime = time();
	include($_SERVER['DOCUMENT_ROOT'].'/includes/dbaccess.php');
//	$todaySecsRemain = 86400 - (date('H', $hitTime)*3600) + (date('i', $hitTime)*60) + date('s', $hitTime);
//	session_set_cookie_params ($todaySecsRemain);
//	session_register(VisitorSessionData);


//header("Cache-control: no-cache"); //for HTTP1.1
//header("Pragma: no-cache");        //for HTTP1.0
//header("Expires: 0");


	$ReqData = GetRequest();
	$outputType = strtolower($ReqData['output']);

	$AllowedIPs = GetParamData('AllowedIPs');
	
	$referringURLRaw = $_SERVER['HTTP_REFERER'];
	
//	$referringURLRaw = 'http://bf.xtrasrv.net/testme.html';
	//http://www3.macserve.net/countertest.html
//	if (empty($referringURL))		$referringURL = 'http://www.bsa214.org';		// debug
	
	$referringURL = explode('/', $referringURLRaw);
	$referringDomain = strtolower($referringURL[2]);
//	echo 'Referring Host Name: '. $referringDomain .'<br>';
	$referringDomainIP = gethostbyname($referringDomain);
//	echo 'Referring Domain IP: '. $referringDomainIP .'<br>';
//	echo 'Referring Domain IP Allowed: '. ($AllowedIPs[$referringDomainIP] ? 'yes' : 'no') .'<br>';
//	exit();

	$verifyReferers = true;
	$acctID = 0;
	if (isset($ReqData['acct']))
	{
		$acct = $ReqData['acct'];
		$whereClause = ($acct+0) ? "AcctID = $acct" : "Nickname = '". addslashes($acct) ."'";
		$AcctData = StdDBSelect('Accounts', '', $whereClause);
		if ($AcctData['Enabled'])
		{
			$acctID = $AcctData['AcctID']+0;
			$verifyReferers = $AcctData['VerifyReferers'];
		}
		else
		{
			ReturnErrorImage('AcctDisabled');
		}
	}
//http://tracker.macserve.net/countertest.x?acct=macserve&name=ebay111&domain=bbebay	
//	if  ($verifyReferers && (! $AllowedIPs[$referringDomainIP] ))		ReturnErrorImage('IPNotAllowed');

	if (in_array($_SERVER['REMOTE_ADDR'], $DebugIPs)) 	$verifyReferers = false;

	if  ($verifyReferers)
	{
		if (empty($referringURLRaw))				ReturnEmpty($outputType);
		
		if (! $AllowedIPs[$referringDomainIP] )
		{		// not an allowed IP
			
			if (!$acctID)				ReturnErrorImage('IPNotAllowed');
//			if (!$acctID)				echo '<span class="">'. "AcctID: $acctID".'</span>';		exit();
		
			//	we have an actual acctid, check for Authd strings in the referrer, (eBay auction num type things)
			$whereClause = "AcctID = $acctID";
			$AuthdURLStrings = StdDBSelectList('AuthdCntrRfrs', 'RecordID,URLString', 'RecordID', 'URLString', $whereClause, '', '');
			$refAuthd = false;
			foreach($AuthdURLStrings as $recID => $urlString)
			{
				if (stristr($referringURLRaw, $urlString))
				{
					$refAuthd = true;
					break;
				}
			}
			if (!$refAuthd)			ReturnErrorImage('IPNotAllowed');
		}
	}


	$counterName = CleanCounterName($ReqData['name']);
	if (empty($ReqData['domain']))
	{	// strip any possible 'www' prefix
		$groupName = trim(str_replace("\rwwww.", '', "\r".$referringDomain));
		$groupName = trim(str_replace("\rwww.", '', "\r".$groupName));
		$groupName = trim(str_replace("\rww.", '', "\r".$groupName));
		if (empty($groupName))		$groupName = 'none';
	}
	else 	$groupName = trim(strtolower($ReqData['domain']));
	$groupName = CleanGroupName($groupName);
	
	$CounterData = StdDBSelect('Counters', '', "(CounterName = '$counterName') AND (GroupName = '$groupName')");
	if (empty($CounterData))		// Counter record doesn't exist, create a new one.
	{
		$CounterData = array('CurValue' => 1, 'CounterName' => $counterName,  'GroupName' => $groupName);
		if (isset($acctID))		$CounterData['AcctID'] = $acctID;
		
		$dbResult = StdDBInsert('Counters', $CounterData);
		$counterID = 0;
		$CounterData['CurValue'] = 0;		// fake it out
	}	else		$counterID = $CounterData['CounterID'];
	
	$counterValue = $CounterData['CurValue']+1;
	
	if (!empty($ReqData['op']))
	{
		$counterOp = trim(strtolower($ReqData['op']));
		if (($counterOp == 'reset') && ($referringDomain == $groupName))		$counterValue = 0;
		if ($counterOp == 'display')	{	$counterValue--;	$counterID = 0; }		// back and no update
	}
	

//	$counterValue = 1512;		// debug code

	if (($outputType == 'text') || !empty($ReqData['class']))
	{
		$cntrOutput = '';
		$textClass = empty($ReqData['class']) ? '' : CleanGroupName($ReqData['class']);
		if (!empty($textClass))
		{
			$cntrOutput = '<span class="'. $textClass .'">'. $counterValue .'</span>';
		}
		else		$cntrOutput = $counterValue;
		echo $cntrOutput;
	}		// end outputting as text
	else
	{		// default to outputting image
//		
		// either the output type wasn't recognized or is of type 'image'
		$numOutDigits = isset($ReqData['width']) ? $ReqData['width']+0 : strlen(' '. $counterValue)-1;
		if ($numOutDigits != 0)
		{
	
			// limit the size of $numOutDigits to 16 digits
			$numOutDigits = min(16, $numOutDigits);
			// get the style of digits we are to use
			$digitStyle = empty($ReqData['style']) ? 'default' : CleanCounterName($ReqData['style']);
			$digitsSrcFile = $_SERVER['DOCUMENT_ROOT']."/digits/$digitStyle.png";
			if (!file_exists($digitsSrcFile))
			{
				$digitStyle = 'default';
				$digitsSrcFile = $_SERVER['DOCUMENT_ROOT']."/digits/$digitStyle.png";
			}

			$DigitsSrcImage = ImageCreateFromPNG($digitsSrcFile);
//			ImagePng($DigitsSrcImage); exit();
			
			$digitsSrcHeight = imagesy($DigitsSrcImage);
			$digitsSrcWidth = imagesx($DigitsSrcImage);
			
//			echo "Height: $digitsSrcHeight - Width: $digitsSrcWidth"; exit();
			$srcDigitWidth = $digitsSrcWidth /10;

			$outputWidth = $numOutDigits * $srcDigitWidth;
			$OutputImage = ImageCreateTrueColor($outputWidth, $digitsSrcHeight);
			$counterValAsText = pow(10, $numOutDigits) + $counterValue;    // 512 + 100000 = 100512 > 00512
			$counterValAsText = substr($counterValAsText, 1) .' ';			// '00512 '
			
			$destY = $srcY = 0;
			for ($index=0; $index < $numOutDigits; $index++)
			{
				$digitNum = $counterValAsText[$index];
				$srcX = $digitNum * $srcDigitWidth;
				$destX = $index * $srcDigitWidth;
				ImageCopy($OutputImage, $DigitsSrcImage, $destX, $destY, $srcX, $srcY, $srcDigitWidth, $digitsSrcHeight);
			}

			$xprntColor = $ReqData['xprc'];
			if (!empty($xprntColor))
			{
				sscanf($xprntColor, "%2x%2x%2x", $red, $green, $blue);		//	"FFFF00"
				$xprntColor = ImageColorAllocate($OutputImage,$red,$green,$blue);
				@ImageColorTransparent($OutputImage, $xprntColor );
			}

// Now output the image
			if (imagetypes() & IMG_GIF)
			{
				header('Content-type: image/gif');
				header("Content-Disposition: inline; filename=\"$groupName-$counterName.gif\"");
				ImageTrueColorToPalette($OutputImage, true, 16);
				$imgOutSuccess = ImageGIF($OutputImage);
			}
			else
			{
				header('Content-type: image/png');
				header("Content-Disposition: inline; filename=\"$groupName-$counterName.png\"");
				$imgOutSuccess = ImagePng($OutputImage);
			}
			if (!$imgOutSuccess)
						error_log("error outputting image $groupName-$counterName.png");
//			ImagePng($OutputImage, $_SERVER['DOCUMENT_ROOT'] ."/dbgout/$groupName-$counterName.png");
			ImageDestroy($OutputImage);
			ImageDestroy($DigitsSrcImage);
		}
		else
		{
			ReturnEmpty($outputType);
		}
	}		// end outputting as image

	ignore_user_abort(true);
	flush();

//		update counter value;
	if ($counterID)
	{
		$UpdateData = ($counterValue) ? array('#CurValue' => 'CurValue +1') : array('CurValue' => 0);
		$dbResult = StdDBUpdate('LOW_PRIORITY Counters', $UpdateData, "CounterID = $counterID", '1');
	}

#error_log("counter -- ID:$counterID, Name:$counterName, Group:$groupName, Value:$counterValue");

	exit();



// ----------------------------

function GetRequest()
{
	return ArrayMerge($_COOKIE, $_POST, $_GET);
}
function ArrayMerge()
{
	$argArray = func_get_args();
	$outArray = $argArray[0];
	$aryNum=-1;
	foreach($argArray as $curAry)	{
		$aryNum++;
		if ($aryNum == 0) continue;
		if (!is_array($curAry)) continue;
			foreach($curAry as $theKey => $theData)	{
				$outArray[$theKey] = $theData;
			}	
		}
	return $outArray;
}

define(kAlphaNumChars, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');

function CleanCounterName($name)	{
	return CleanString(strtolower($name), (kAlphaNumChars .'-'));
}
function CleanGroupName($name)	{
	return CleanString($name, (kAlphaNumChars .'-.'));
}
function CleanString($theString, $cleanChars)
{
	$cleanStr = '';
	$dataLen = strlen($theString);
	for ($index=0; $index < $dataLen; $index++)
	{
		$pos = strpos($cleanChars, $theString[$index]);
		if ( ! ($pos === false) )		$cleanStr .= $theString[$index];
	}
	return $cleanStr;
}

function ReturnErrorImage($errType='')
{
	$errStr = $_SERVER['HTTP_HOST'] ."->". $_SERVER['HTTP_REFERER'] ."->". $_SERVER['REMOTE_ADDR'];
	error_log("Tracker-$errType: ". $errStr);
	switch ($errType)
	{
		case 'IPNotAllowed':
			header('Content-type: image/gif');
			header('Content-Disposition: inline; filename="x.gif"');
			header('Content-Length: 3729');
			readfile($_SERVER['DOCUMENT_ROOT'].'/digits/boo.gif');
			break;
		case 'AcctDisabled':
			header('Content-type: image/gif');
			header('Content-Disposition: inline; filename="x.gif"');
			header('Content-Length: 3729');
			readfile($_SERVER['DOCUMENT_ROOT'].'/digits/boo.gif');
			break;
	}
	exit();
}

function ReturnEmpty($outputType)
{
	if ($outputType == "text")
	{
		echo " ";
	}
	else
	{		// output 1x1 transparent gif
		header('Content-type: image/gif');
		header('Content-Disposition: inline; filename="x.gif"');
		header('Content-Length: 43');
		readfile($_SERVER['DOCUMENT_ROOT'].'/digits/nofont.gif');
	}
	exit();
}

function GetParamData($dataKey)
{
	$ParamData = StdDBSelect('Params', '', "ParamKey = '$dataKey'");
	return unserialize($ParamData['ParamValue']);
}
function SetParamData($dataKey, $theData)
{
	return StdDBUpdate('Params', array('ParamValue' => serialize($theData)), "ParamKey = '$dataKey'", '1');
}




//	$reqDataText = '';
//	foreach($ReqData as $fldName => $fldValue)
//	{
//		$reqDataText .= "$fldName => $fldValue\r";
//	}
//	LogError('Hit', $reqDataText);
//	echo $reqDataText;


# page=PAGE_NAME       The NAME can be any text string you like (no spaces).  
#                      If unspecified the pages path/name is taken from 
#                      the DOCUMENT_URI environment variable (SSI)
#                      or the HTTP_REFERER variable (non-SSI).    
# style=STYLE_NAME     The style of digits to be used in the counter.
#                      "text" is the default. Other options are given by 
#                      the names of the subdirectories in the $digits_dir.
#                      Currently: "LED", "LED_g", "LED_r", "odometer",
#                      "odometer_sm", "curly", "rosewood"...  
#                      More GIFs can be added, just create the coresponding
#                      directory and the "size" file containing: 
#                      <GIF width>x<GIF height> (all digits within a
#                      style must be the same size). 
# show=counter   displays "[counter value]"  (default action)
# show=all       displays "[counter value] hits since [date initalized]"       
# show=date      displays just the "[date initialized]", no counter increment 
# show=nothing   displays nothing, but does increment the counter file 
# hidden=1       same effect 
# invisible=1    same effect
# digits=N       pads the counter with left zeros to be at least N digits 
# commas=0       remove commas from text counter
# trans=r,g,b    rgb color to make transparent
# link=1         adds a hyperlink around the counter to $LINKURI
# align=[top][middle][bottom] alignment of text after counter (bottom default)
# increment=0    no counter increment (in case of multiple counters on a page)
# block=N        block incrementing from consecutive reloads for N seconds
# header=0       when calling this script from another CGI script (passing 
#                the page name via the URI_DOCUMENT variable and options
#                via the QUERY_STRING variable) set header=0, allowing
#                the calling script to output the HTTP header.
# the next two options only need to be given (if desired) upon initial use:
# start=NUM         initialize counter to the starting value NUM
# start_date=DATE   initialize counter to the starting date DATE (any format)


return;
?>
