PR CI / ledger (pull_request) Successful in 4s
PR CI / flow (pull_request) Successful in 5s
PR CI / test (lowest) (pull_request) Successful in 37s
PR CI / test (stable) (pull_request) Successful in 37s
PR CI / security (pull_request) Successful in 51s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Failing after 4s
66 lines
2.3 KiB
PHP
66 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Statistics;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use IriksIT\Manager\Support\UserAgent;
|
|
|
|
/**
|
|
* Counts the programs that fetch pages: search engines, AI crawlers, link
|
|
* previews, monitors, scripts. The only code that writes to `bot_hits`.
|
|
*
|
|
* A program never runs the script that reports a page view, so it is seen here,
|
|
* on the server, while the page is served (CountBots). All that is kept is a
|
|
* counter per day, program and page: no address, no browser line, nothing that
|
|
* could be a person. The visitor statistics themselves never hold a program.
|
|
*/
|
|
final class BotRecorder
|
|
{
|
|
/** A program without a name of its own, or one too many. */
|
|
public const OTHER = 'Other';
|
|
|
|
/**
|
|
* Names that are not in the list of UserAgent come from the request, so
|
|
* anyone can make them up. After this many different ones in a day the rest
|
|
* is filed under "Other": the table cannot be filled with invented names.
|
|
*/
|
|
public const UNKNOWN_NAMES_A_DAY = 100;
|
|
|
|
/** Counts one page that was served to a program. Does nothing for a person. */
|
|
public function hit(string $userAgent, string $path): void
|
|
{
|
|
$table = config('manager.table_prefix').'bot_hits';
|
|
$bot = (new UserAgent($userAgent))->bot();
|
|
|
|
if ($bot === null) {
|
|
return;
|
|
}
|
|
|
|
$day = now()->toDateString();
|
|
$name = $bot['name'] ?? self::OTHER;
|
|
|
|
if ($bot['kind'] === 'other' && $name !== self::OTHER && $this->isOneTooMany($table, $day, $name)) {
|
|
$name = self::OTHER;
|
|
}
|
|
|
|
// One statement, so two requests at the same moment both count.
|
|
DB::table($table)->upsert(
|
|
[['day' => $day, 'bot' => $name, 'kind' => $bot['kind'], 'path' => Str::limit('/'.trim(Str::before($path, '?'), '/'), 255, ''), 'hits' => 1]],
|
|
['day', 'bot', 'path'],
|
|
['hits' => DB::raw($table.'.hits + 1')],
|
|
);
|
|
}
|
|
|
|
private function isOneTooMany(string $table, string $day, string $name): bool
|
|
{
|
|
$unknown = DB::table($table)->where('day', $day)->where('kind', 'other');
|
|
|
|
if ((clone $unknown)->where('bot', $name)->exists()) {
|
|
return false;
|
|
}
|
|
|
|
return $unknown->distinct()->count('bot') >= self::UNKNOWN_NAMES_A_DAY;
|
|
}
|
|
}
|