Removes logging logic from index and replaces old log class with a wrapper

main
Yasen Pramatarov 2025-04-25 10:20:57 +03:00
parent ff28ebf753
commit e8576d3e94
2 changed files with 44 additions and 115 deletions

View File

@ -1,126 +1,42 @@
<?php
/**
* class Log
*
* Handles logging events into a database and reading log entries.
* Log wrapper that delegates to plugin Log or NullLogger fallback.
* Used when code does require_once '../app/classes/log.php'.
*/
// If there is already a Log plugin loaded
if (class_exists('Log')) {
return;
}
// Load fallback NullLogger
require_once __DIR__ . '/../core/NullLogger.php';
class Log {
/**
* @var PDO|null $db The database connection instance.
*/
private $db;
private $logger;
/**
* Logs constructor.
* Initializes the database connection.
*
* @param object $database The database object to initialize the connection.
* @param mixed $database Database or DatabaseConnector instance
*/
public function __construct($database) {
if ($database instanceof PDO) {
$this->db = $database;
global $logObject;
if (isset($logObject) && method_exists($logObject, 'insertLog')) {
$this->logger = $logObject;
} else {
$this->db = $database->getConnection();
$this->logger = new \App\Core\NullLogger();
}
}
/**
* Insert a log event into the database.
* Delegate insertLog to underlying logger
*
* @param int $userId The ID of the user associated with the log event.
* @param string $message The log message to insert.
* @param string $scope The scope of the log event (e.g., 'user', 'system'). Default is 'user'.
*
* @return bool|string True on success, or an error message on failure.
* @param mixed $userId
* @param string $message
* @param string|null $scope
* @return mixed True on success or error message
*/
public function insertLog($userId, $message, $scope='user') {
try {
$sql = 'INSERT INTO logs
(user_id, scope, message)
VALUES
(:user_id, :scope, :message)';
$query = $this->db->prepare($sql);
$query->execute([
':user_id' => $userId,
':scope' => $scope,
':message' => $message,
]);
return true;
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
* Retrieve log entries from the database.
*
* @param int $userId The ID of the user whose logs are being retrieved.
* @param string $scope The scope of the logs ('user' or 'system').
* @param int $offset The offset for pagination. Default is 0.
* @param int $items_per_page The number of log entries to retrieve per page. Default is no limit.
* @param array $filters Optional array of filters (from_time, until_time, message, id)
*
* @return array An array of log entries.
*/
public function readLog($userId, $scope, $offset=0, $items_per_page='', $filters=[]) {
$params = [];
$where_clauses = [];
// Base query with user join
$base_sql = 'SELECT l.*, u.username
FROM logs l
LEFT JOIN users u ON l.user_id = u.id';
// Add scope condition
if ($scope === 'user') {
$where_clauses[] = 'l.user_id = :user_id';
$params[':user_id'] = $userId;
}
// Add time range filters if specified
if (!empty($filters['from_time'])) {
$where_clauses[] = 'l.time >= :from_time';
$params[':from_time'] = $filters['from_time'] . ' 00:00:00';
}
if (!empty($filters['until_time'])) {
$where_clauses[] = 'l.time <= :until_time';
$params[':until_time'] = $filters['until_time'] . ' 23:59:59';
}
// Add message search if specified
if (!empty($filters['message'])) {
$where_clauses[] = 'l.message LIKE :message';
$params[':message'] = '%' . $filters['message'] . '%';
}
// Add user ID search if specified
if (!empty($filters['id'])) {
$where_clauses[] = 'l.user_id = :search_user_id';
$params[':search_user_id'] = $filters['id'];
}
// Combine WHERE clauses
$sql = $base_sql;
if (!empty($where_clauses)) {
$sql .= ' WHERE ' . implode(' AND ', $where_clauses);
}
// Add ordering
$sql .= ' ORDER BY l.time DESC';
// Add pagination
if ($items_per_page) {
$items_per_page = (int)$items_per_page;
$sql .= ' LIMIT ' . $offset . ',' . $items_per_page;
}
$query = $this->db->prepare($sql);
$query->execute($params);
return $query->fetchAll(PDO::FETCH_ASSOC);
public function insertLog($userId, string $message, ?string $scope = null) {
return $this->logger->insertLog($userId, $message, $scope);
}
}

View File

@ -99,7 +99,6 @@ $allowed_urls = [
'settings',
'security',
'status',
'logs',
'help',
'login',
@ -135,18 +134,32 @@ $public_pages = filter_public_pages($public_pages);
// Dispatch routing and auth
require_once __DIR__ . '/../app/core/Router.php';
$currentUser = \App\Core\Router::checkAuth($config, $app_root, $public_pages, $page);
use App\Core\Router;
$currentUser = Router::checkAuth($config, $app_root, $public_pages, $page);
// connect to DB via DatabaseConnector
require_once __DIR__ . '/../app/core/DatabaseConnector.php';
use App\Core\DatabaseConnector;
$dbWeb = DatabaseConnector::connect($config);
// start logging
require '../app/classes/log.php';
include '../app/helpers/logs.php';
$logObject = new Log($dbWeb);
$user_IP = getUserIP();
// Logging: default to NullLogger, plugin can override
require_once __DIR__ . '/../app/core/NullLogger.php';
use App\Core\NullLogger;
$logObject = new NullLogger();
// Get the user IP
require_once __DIR__ . '/../app/helpers/ip_helper.php';
$user_IP = '';
// Plugin: initialize logging system plugin if available
do_hook('logger.system_init', ['db' => $dbWeb]);
// Override defaults if plugin provided real logger
if (isset($GLOBALS['logObject'])) {
$logObject = $GLOBALS['logObject'];
}
if (isset($GLOBALS['user_IP'])) {
$user_IP = $GLOBALS['user_IP'];
}
// Initialize security middleware
require_once '../app/includes/csrf_middleware.php';