fwdkr.co/dist/goatcounter.php

60 lines
1.7 KiB
PHP

<?php
/**
* Returns true if GoatCounter should process the current request.
*
* @return bool true if GoatCounter should process the current request
*/
function goatcounter_should_process(): bool
{
if (!is_readable(".goat.token") || !is_readable(".goat.url")) return false;
if (is_readable(".goat.ignore")) {
$ignored_ips = file(".goat.ignore", FILE_IGNORE_NEW_LINES);
if (in_array($_SERVER["REMOTE_ADDR"], $ignored_ips)) return false;
}
if (isset($_SERVER["HTTP_USER_AGENT"])
&& preg_match("/bot|crawl|slurp|spider|mediapartners/i", $_SERVER["HTTP_USER_AGENT"])) return false;
return true;
}
/**
* Sends a request to this website's GoatCounter server to record a hit.
*
* @param $path string the path to record a hit for
*/
function goatcounter_record_hit(string $path)
{
if (!goatcounter_should_process()) return;
$token = str_replace(["\r\n", "\r", "\n"], "", file_get_contents(".goat.token"));
$url = str_replace(["\r\n", "\r", "\n"], "", file_get_contents(".goat.url"));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode(array(
"hits" => array(array(
"path" => $path,
"ip" => $_SERVER["REMOTE_ADDR"],
"ref" => $_SERVER["HTTP_REFERER"] ?? "",
"user_agent" => $_SERVER["HTTP_USER_AGENT"]
))
))
);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
"Content-Type: application/json",
"Authorization: Bearer $token"
)
);
curl_exec($ch);
curl_close($ch);
}