Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions app/Http/Controllers/Counter/CounterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,31 @@
use App\Models\Visitor;
use App\Models\CounterPage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Profil;

class CounterController extends Controller
{
private const CACHE_TOP_PAGES = 'counter.top_pages';

private const CACHE_TTL_MINUTES = 5;

public function index()
{
$page_title = 'Statistik Pengunjung';
$page_description = 'Jumlah Statistik Pengunjung Website';

// hitung statistik
// hitung statistik: enam periode dalam satu query, di-cache agar tidak dihitung ulang setiap buka halaman
$summary = Visitor::cachedSummaryStats();
$visitors = [
'todayVisitors' => Visitor::stats(VisitorFilterEnum::TODAY),
'yesterdayVisitors' => Visitor::stats(VisitorFilterEnum::YESTERDAY),
'weeklyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_WEEK),
'monthlyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_MONTH),
'yearlyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_YEAR),
'totalVisitors' => Visitor::stats(VisitorFilterEnum::ALL),
'todayVisitors' => $summary['today'],
'yesterdayVisitors' => $summary['yesterday'],
'weeklyVisitors' => $summary['thisWeek'],
'monthlyVisitors' => $summary['thisMonth'],
'yearlyVisitors' => $summary['thisYear'],
'totalVisitors' => $summary['all'],
];

// request url query parameter 'filter'
Expand All @@ -67,7 +73,7 @@ public function index()
];

// Halaman populer
$top_pages_visited = Visitor::getTopPagesVisited();
$top_pages_visited = Cache::remember(self::CACHE_TOP_PAGES, now()->addMinutes(self::CACHE_TTL_MINUTES), fn () => Visitor::getTopPagesVisited());

return view('counter.index', compact(
'page_title',
Expand Down
8 changes: 4 additions & 4 deletions app/Http/Middleware/TrackVisitors.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ public function handle(Request $request, Closure $next)
$ipAddress = $request->ip();
$hashedIpAddress = hash('sha256', $ipAddress); // Hash IP address
$url = $request->fullUrl();
$today = now()->toDateString();
$userAgent = $request->userAgent();

$visitor = Visitor::where('ip_address', $hashedIpAddress)
->where('url', $url)
->whereDate('visited_at', $today)
// Lookup memakai index (ip_address, url_hash, visited_at), bukan membandingkan kolom TEXT url.
$visitor = Visitor::filter(\App\Enums\VisitorFilterEnum::TODAY)
->where('ip_address', $hashedIpAddress)
->where('url_hash', hash('sha256', $url))
->first();

if ($visitor) {
Expand Down
108 changes: 93 additions & 15 deletions app/Models/Visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,100 @@ class Visitor extends Model
'visited_at' => 'datetime',
];

/* Query scope filter date */
protected static function booted(): void
{
// url_hash menjadi kunci pengelompokan dan lookup, karena kolom url berupa TEXT (tidak bisa di-index penuh).
static::saving(function (Visitor $visitor) {
if ($visitor->isDirty('url') && $visitor->url !== null) {
$visitor->url_hash = hash('sha256', $visitor->url);
}
});
}

/* Query scope filter date. Memakai rentang [awal, akhir) agar index visited_at bisa dipakai. */
public function scopeFilter($query, $filter = null)
{
switch ($filter) {
case VisitorFilterEnum::YESTERDAY:
$query->whereDate('visited_at', Carbon::yesterday());
break;
$start = Carbon::yesterday()->startOfDay();
return self::applyRange($query, $start, $start->copy()->addDay());
case VisitorFilterEnum::THIS_WEEK:
$query->whereBetween('visited_at', [now()->startOfWeek(), now()->endOfWeek()]);
break;
$start = now()->startOfWeek();
return self::applyRange($query, $start, $start->copy()->addWeek());
case VisitorFilterEnum::THIS_MONTH:
$query->whereMonth('visited_at', now()->month)
->whereYear('visited_at', now()->year);
break;
$start = now()->startOfMonth();
return self::applyRange($query, $start, $start->copy()->addMonth());
case VisitorFilterEnum::THIS_YEAR:
$query->whereYear('visited_at', now()->year);
break;
$start = now()->startOfYear();
return self::applyRange($query, $start, $start->copy()->addYear());
case VisitorFilterEnum::ALL:
// tidak ada filter
break;
default:
$query->whereDate('visited_at', Carbon::today());
$start = Carbon::today();
return self::applyRange($query, $start, $start->copy()->addDay());
}

return $query;
}

private static function applyRange($query, Carbon $start, Carbon $end)
{
return $query->where('visited_at', '>=', $start)->where('visited_at', '<', $end);
}

/**
* Ringkasan enam periode dalam satu kali pemindaian tabel.
* Mengembalikan array dengan kunci: today, yesterday, thisWeek, thisMonth, thisYear, all.
* Setiap nilai berupa object dengan properti page_views dan unique_visitors.
*/
public static function summaryStats(): array
{
$now = now();
$todayStart = $now->copy()->startOfDay();
$weekStart = $now->copy()->startOfWeek();
$monthStart = $now->copy()->startOfMonth();
$yearStart = $now->copy()->startOfYear();

$periods = [
'today' => [$todayStart, $todayStart->copy()->addDay()],
'yesterday' => [$todayStart->copy()->subDay(), $todayStart],
'thisWeek' => [$weekStart, $weekStart->copy()->addWeek()],
'thisMonth' => [$monthStart, $monthStart->copy()->addMonth()],
'thisYear' => [$yearStart, $yearStart->copy()->addYear()],
'all' => null,
];

$columns = [];
$bindings = [];
foreach ($periods as $key => $range) {
if ($range === null) {
$columns[] = "SUM(page_views) AS {$key}_page_views";
$columns[] = "COUNT(DISTINCT ip_address) AS {$key}_unique_visitors";

continue;
}

[$start, $end] = $range;
$condition = 'visited_at >= ? AND visited_at < ?';
$columns[] = "SUM(CASE WHEN {$condition} THEN page_views ELSE 0 END) AS {$key}_page_views";
$columns[] = "COUNT(DISTINCT CASE WHEN {$condition} THEN ip_address END) AS {$key}_unique_visitors";
array_push($bindings, $start, $end, $start, $end);
}

$row = self::query()->selectRaw(implode(', ', $columns), $bindings)->first();

$summary = [];
foreach (array_keys($periods) as $key) {
$summary[$key] = (object) [
'page_views' => (int) $row->{"{$key}_page_views"},
'unique_visitors' => (int) $row->{"{$key}_unique_visitors"},
];
}

return $summary;
}

public static function stats($filter = null)
{
return self::filter($filter)
Expand Down Expand Up @@ -75,21 +142,32 @@ public static function groupedStats($filter)
->get();
}

/* data untuk halaman populer */
/* data untuk halaman populer. Dikelompokkan per url_hash (indexed), bukan url (TEXT). */
public static function getTopPagesVisited()
{
return self::select('url')
return self::select('url_hash')
->selectRaw('MAX(url) as url')
->selectRaw('SUM(page_views) as total_views')
->selectRaw('COUNT(DISTINCT ip_address) as unique_visitors')
->selectRaw('SUM(CASE WHEN page_views = 1 THEN 1 ELSE 0 END) as bounces')
->groupBy('url')
->groupBy('url_hash')
->orderByDesc('total_views')
->limit(10)
->get();
}

/* Ringkasan di-cache bersama, sehingga sidebar (dipanggil di setiap halaman admin) tidak memindai tabel lagi. */
public static function cachedSummaryStats(): array
{
return \Illuminate\Support\Facades\Cache::remember(
'counter.summary',
now()->addMinutes(5),
fn () => self::summaryStats()
);
}

public static function countAllVisitors()
{
return \Illuminate\Support\Facades\DB::table('visitors')->distinct('ip_address')->count('ip_address');
return self::cachedSummaryStats()['all']->unique_visitors;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/*
* Menambahkan kolom url_hash (sha256 dari url) dan index pada tabel visitors
* agar statistik pengunjung tidak memindai seluruh tabel (issue #1817).
*/
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasColumn('visitors', 'url_hash')) {
Schema::table('visitors', function (Blueprint $table) {
$table->char('url_hash', 64)->nullable()->after('url');
});
}

// Backfill data lama. SHA2 dijalankan di sisi database agar tidak memuat 500 ribu baris ke PHP.
DB::statement('UPDATE visitors SET url_hash = SHA2(url, 256) WHERE url_hash IS NULL');

Schema::table('visitors', function (Blueprint $table) {
$table->index('visited_at', 'visitors_visited_at_index');
$table->index('url_hash', 'visitors_url_hash_index');
$table->index(['ip_address', 'url_hash', 'visited_at'], 'visitors_ip_url_visited_index');
});
}

public function down(): void
{
Schema::table('visitors', function (Blueprint $table) {
$table->dropIndex('visitors_visited_at_index');
$table->dropIndex('visitors_url_hash_index');
$table->dropIndex('visitors_ip_url_visited_index');
});

Schema::table('visitors', function (Blueprint $table) {
$table->dropColumn('url_hash');
});
}
};
Loading
Loading