Script cek total user online Moodle

Script ini berfungsi untuk cek total user online di Moodle melalui command line buat monitoring:

buat file di dalam direktori admin/cli/online.php, isinya:

<?php
define('CLI_SCRIPT', true);
require(__DIR__ . '/../../config.php');

$threshold = time() - 300; // 5 menit terakhir

// Ambil user online
$users = $DB->get_records_sql("
    SELECT u.id, u.username, u.firstname, u.lastname, ula.timeaccess
    FROM {user} u
    JOIN {user_lastaccess} ula ON u.id = ula.userid
    WHERE ula.timeaccess > ?
    ORDER BY ula.timeaccess DESC
", [$threshold]);

$total = count($users);

// Fungsi pembuat garis
function line($lengths) {
    $line = "+";
    foreach ($lengths as $len) {
        $line .= str_repeat("-", $len + 2) . "+";
    }
    return $line . "\n";
}

// Tentukan lebar kolom
$widths = [
    'ID' => 5,
    'Username' => 20,
    'Name' => 30,
    'LastAccess' => 20
];

// Sesuaikan lebar kolom berdasarkan data terpanjang
foreach ($users as $u) {
    $widths['Username'] = max($widths['Username'], strlen($u->username));
    $fullname = $u->firstname . ' ' . $u->lastname;
    $widths['Name'] = max($widths['Name'], strlen($fullname));
}

// Header
echo line($widths);
echo sprintf(
    "| %-{$widths['ID']}s | %-{$widths['Username']}s | %-{$widths['Name']}s | %-{$widths['LastAccess']}s |\n",
    "ID", "Username", "Name", "Last Access"
);
echo line($widths);

// Isi tabel
if ($total > 0) {
    foreach ($users as $u) {
        $fullname = $u->firstname . ' ' . $u->lastname;
        echo sprintf(
            "| %-{$widths['ID']}s | %-{$widths['Username']}s | %-{$widths['Name']}s | %-{$widths['LastAccess']}s |\n",
            $u->id,
            $u->username,
            $fullname,
            date('Y-m-d H:i', $u->timeaccess)
        );
    }
} else {
    echo "| Tidak ada user online. |\n";
}

echo line($widths);

echo "\nTotal users online: $total\n";

Cara menjalankan

php admin/cli/online.php

Contoh hasilnya nanti ada table dan hasil total user online

Total users online: 491

Semoga bermanfaat.

Add a comment

Exit mobile version