Statistics module: visitor statistics without cookies
This commit is contained in:
1 parent
acb8620621
commit
7482ee489b
24 files changed
+1872
-4
No files matched your search
@@ -0,0 +1,65 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user