Add clear logs functionality

This commit is contained in:
Vontainment 2025-07-09 10:47:30 -04:00
parent 57412bc163
commit f63c948c25
3 changed files with 48 additions and 0 deletions

View file

@ -15,6 +15,7 @@
namespace App\Controllers;
use App\Core\Controller;
use App\Core\ErrorMiddleware;
use App\Models\LogModel;
class LogsController extends Controller
@ -28,6 +29,25 @@ class LogsController extends Controller
*/
public static function handleRequest(): void
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (
isset($_POST['csrf_token'], $_SESSION['csrf_token']) &&
hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
) {
if (isset($_POST['clear_logs'])) {
LogModel::clearAllLogs();
$_SESSION['messages'][] = 'Logs cleared successfully.';
}
header('Location: /logs');
exit();
}
$error = 'Invalid Form Action.';
ErrorMiddleware::logMessage($error);
$_SESSION['messages'][] = $error;
header('Location: /logs');
exit();
}
$ploutput = LogModel::processLogFile('plugin.log');
$thoutput = LogModel::processLogFile('theme.log');

View file

@ -77,4 +77,28 @@ class LogModel
return 'Log file not found.';
}
/**
* Clear the contents of a log file without deleting it.
*
* @param string $logFile The log file name.
*
* @return bool True on success, false otherwise.
*/
public static function clearLogFile(string $logFile): bool
{
$log_file_path = self::$dir . "/$logFile";
return file_exists($log_file_path) ? file_put_contents($log_file_path, '') !== false : false;
}
/**
* Clear all known logs.
*
* @return void
*/
public static function clearAllLogs(): void
{
self::clearLogFile('plugin.log');
self::clearLogFile('theme.log');
}
}

View file

@ -20,5 +20,9 @@ require_once __DIR__ . '/layouts/header.php';
<?php echo $ploutput; ?>
<h2>Theme Log</h2>
<?php echo $thoutput; ?>
<form method="post" action="/logs" style="margin-top:20px;">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
<button class="red-button" type="submit" name="clear_logs">Clear Logs</button>
</form>
</div>
<?php require_once __DIR__ . '/layouts/footer.php'; ?>