51 lines
1.5 KiB
PHP
51 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Statistics;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Throwable;
|
|
|
|
/**
|
|
* Counts the public pages that are served to a program (see BotRecorder). Only a
|
|
* page that exists and was served: an address that is made up, a redirect and the
|
|
* manager are left out, so the list of pages cannot be filled with nonsense.
|
|
*/
|
|
class CountBots
|
|
{
|
|
public function __construct(private readonly BotRecorder $recorder) {}
|
|
|
|
/**
|
|
* @param Closure(Request): Response $next
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$response = $next($request);
|
|
|
|
if ($this->counts($request, $response)) {
|
|
try {
|
|
$this->recorder->hit((string) $request->userAgent(), $request->getPathInfo());
|
|
} catch (Throwable $e) {
|
|
// Counting must never be the reason a page is not served.
|
|
report($e);
|
|
}
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
private function counts(Request $request, Response $response): bool
|
|
{
|
|
$name = $request->route()?->getName();
|
|
|
|
return $request->isMethod('GET')
|
|
&& $response->getStatusCode() === 200
|
|
&& is_string($name)
|
|
&& ! str_starts_with($name, 'manager.')
|
|
// The same promise as for visitors: who asks not to be followed is not counted at all.
|
|
&& $request->header('Sec-GPC') !== '1'
|
|
&& $request->header('DNT') !== '1';
|
|
}
|
|
}
|