Compare commits
No commits in common. "eb4b5ca7bcba02d559c728dcb2b7b9f7126c70d5" and "d318b621d51861baaceed70101fc2b7cce8160b2" have entirely different histories.
eb4b5ca7bc
...
d318b621d5
|
|
@ -603,41 +603,25 @@ if ($queryAction === 'plugin_check_page' && isset($_GET['plugin'])) {
|
|||
|
||||
// Check database tables
|
||||
$db = \App\App::db();
|
||||
$pluginOwnedTables = [];
|
||||
$pluginReferencedTables = [];
|
||||
if ($db && method_exists($db, 'getConnection')) {
|
||||
$pdo = $db->getConnection();
|
||||
$stmt = $pdo->query("SHOW TABLES");
|
||||
$pluginTables = [];
|
||||
if ($db instanceof PDO) {
|
||||
$stmt = $db->query("SHOW TABLES");
|
||||
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
||||
|
||||
if ($hasMigration) {
|
||||
// Check each migration file for table references
|
||||
foreach ($migrationFiles as $migrationFile) {
|
||||
$migrationContent = file_get_contents($migrationFile);
|
||||
|
||||
// Extract tables created by this migration (plugin-owned)
|
||||
if (preg_match_all('/CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+`?([a-zA-Z0-9_]+)`?/i', $migrationContent, $matches)) {
|
||||
foreach ($matches[1] as $tableName) {
|
||||
if (in_array($tableName, $allTables)) {
|
||||
$pluginOwnedTables[] = $tableName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find all referenced tables (dependencies)
|
||||
foreach ($allTables as $table) {
|
||||
if (strpos($migrationContent, $table) !== false && !in_array($table, $pluginOwnedTables)) {
|
||||
$pluginReferencedTables[] = $table;
|
||||
if (strpos($migrationContent, $table) !== false) {
|
||||
$pluginTables[] = $table;
|
||||
}
|
||||
}
|
||||
}
|
||||
$pluginOwnedTables = array_unique($pluginOwnedTables);
|
||||
$pluginReferencedTables = array_unique($pluginReferencedTables);
|
||||
$pluginTables = array_unique($pluginTables);
|
||||
}
|
||||
}
|
||||
$checkResults['tables'] = [
|
||||
'owned' => $pluginOwnedTables,
|
||||
'referenced' => $pluginReferencedTables,
|
||||
];
|
||||
$checkResults['tables'] = $pluginTables;
|
||||
|
||||
// Check plugin functions
|
||||
$bootstrapPath = $pluginInfo['path'] . '/bootstrap.php';
|
||||
|
|
|
|||
|
|
@ -628,41 +628,25 @@ endif; ?>
|
|||
|
||||
// Check database tables
|
||||
$db = \App\App::db();
|
||||
$pluginOwnedTables = [];
|
||||
$pluginReferencedTables = [];
|
||||
if ($db && method_exists($db, 'getConnection')) {
|
||||
$pdo = $db->getConnection();
|
||||
$stmt = $pdo->query("SHOW TABLES");
|
||||
$pluginTables = [];
|
||||
if ($db instanceof PDO) {
|
||||
$stmt = $db->query("SHOW TABLES");
|
||||
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
||||
|
||||
if ($hasMigration) {
|
||||
// Check each migration file for table references
|
||||
foreach ($migrationFiles as $migrationFile) {
|
||||
$migrationContent = file_get_contents($migrationFile);
|
||||
|
||||
// Extract tables created by this migration (plugin-owned)
|
||||
if (preg_match_all('/CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+`?([a-zA-Z0-9_]+)`?/i', $migrationContent, $matches)) {
|
||||
foreach ($matches[1] as $tableName) {
|
||||
if (in_array($tableName, $allTables)) {
|
||||
$pluginOwnedTables[] = $tableName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find all referenced tables (dependencies)
|
||||
foreach ($allTables as $table) {
|
||||
if (strpos($migrationContent, $table) !== false && !in_array($table, $pluginOwnedTables)) {
|
||||
$pluginReferencedTables[] = $table;
|
||||
if (strpos($migrationContent, $table) !== false) {
|
||||
$pluginTables[] = $table;
|
||||
}
|
||||
}
|
||||
}
|
||||
$pluginOwnedTables = array_unique($pluginOwnedTables);
|
||||
$pluginReferencedTables = array_unique($pluginReferencedTables);
|
||||
$pluginTables = array_unique($pluginTables);
|
||||
}
|
||||
}
|
||||
$checkResults['tables'] = [
|
||||
'owned' => $pluginOwnedTables,
|
||||
'referenced' => $pluginReferencedTables,
|
||||
];
|
||||
$checkResults['tables'] = $pluginTables;
|
||||
|
||||
// Check plugin functions and integrations
|
||||
$bootstrapPath = $plugin['path'] . '/bootstrap.php';
|
||||
|
|
@ -789,29 +773,13 @@ endif; ?>
|
|||
<h6 class="card-title mb-0">Database Tables</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<?php if (!empty($checkResults['tables']['owned']) || !empty($checkResults['tables']['referenced'])): ?>
|
||||
<?php if (!empty($checkResults['tables']['owned'])): ?>
|
||||
<div class="mb-3">
|
||||
<strong class="text-danger">Plugin Tables (removed on purge):</strong>
|
||||
<?php foreach ($checkResults['tables']['owned'] as $table): ?>
|
||||
<div class="d-flex justify-content-between align-items-center mb-2 mt-2">
|
||||
<span><i class="fas fa-database text-danger"></i> <?= htmlspecialchars($table) ?></span>
|
||||
<span class="badge bg-danger">Owned</span>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php if (!empty($checkResults['tables'])): ?>
|
||||
<?php foreach ($checkResults['tables'] as $table): ?>
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<span><?= htmlspecialchars($table) ?></span>
|
||||
<span class="badge bg-success">Present</span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if (!empty($checkResults['tables']['referenced'])): ?>
|
||||
<div>
|
||||
<strong class="text-muted">Referenced Tables (dependencies):</strong>
|
||||
<?php foreach ($checkResults['tables']['referenced'] as $table): ?>
|
||||
<div class="d-flex justify-content-between align-items-center mb-2 mt-2">
|
||||
<span><i class="fas fa-link text-muted"></i> <?= htmlspecialchars($table) ?></span>
|
||||
<span class="badge bg-secondary">Referenced</span>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<p class="text-muted mb-0">
|
||||
<?php if ($checkResults['files']['migration']): ?>
|
||||
|
|
|
|||
|
|
@ -1,38 +1,13 @@
|
|||
# Logger plugin
|
||||
|
||||
## Overview
|
||||
The Logger plugin (located in `plugins/logs/`) provides a modular, pluggable logging
|
||||
system for the application. It records both user and system events in the `log`
|
||||
table and exposes retrieval utilities plus a built-in UI at `?page=logs`.
|
||||
|
||||
The plugin uses the callable dispatcher pattern with `PluginRouteRegistry` for routing
|
||||
and follows the App API pattern for service access.
|
||||
|
||||
## Features
|
||||
1. **Log entry management**
|
||||
- PSR-3-style `log()` method with level + context payloads
|
||||
- Core helper `app_log()` for simplified access with NullLogger fallback
|
||||
2. **Filtering & pagination**
|
||||
- Query by scope, user, time range, message text, or specific user IDs
|
||||
- Pagination-ready result sets with newest-first sorting
|
||||
3. **User awareness**
|
||||
- Stores username via joins for auditing
|
||||
- Captures current user IP via plugin bootstrap
|
||||
4. **Auto-migration**
|
||||
- `logs_ensure_tables()` function creates the `log` table on demand
|
||||
- Called automatically via `logger.system_init` hook
|
||||
5. **UI integration**
|
||||
- Adds a "Logs" entry to the top menu
|
||||
- Provides list/detail views with tabs for user vs system scopes
|
||||
- Uses callable dispatcher for route handling
|
||||
The Logger plugin provides a modular, pluggable logging system for the application.
|
||||
It logs user and system events to a MySQL table named `log`.
|
||||
|
||||
## Installation
|
||||
1. Copy the `logs` folder into the project's `plugins/` directory.
|
||||
2. Enable the plugin via the admin plugin management interface (stored in `settings` table).
|
||||
3. The plugin bootstrap automatically:
|
||||
- Registers the `logs` route prefix with a callable dispatcher
|
||||
- Sets up the `logs_ensure_tables()` migration function
|
||||
- Initializes the logger via the `logger.system_init` hook
|
||||
1. Copy the entire `logger` folder into your project's `plugins/` directory.
|
||||
2. Ensure `"enabled": true` in `plugins/logger/plugin.json`.
|
||||
3. On first initialization, the plugin will create the `log` table if it does not already exist.
|
||||
|
||||
## Database Schema
|
||||
The plugin defines the following table (auto-created):
|
||||
|
|
@ -49,120 +24,39 @@ CREATE TABLE IF NOT EXISTS `log` (
|
|||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
|
||||
```
|
||||
|
||||
## Routing & Dispatcher
|
||||
The plugin registers its route using `PluginRouteRegistry`:
|
||||
```php
|
||||
register_plugin_route_prefix('logs', [
|
||||
'dispatcher' => function($action, array $context = []) {
|
||||
require_once PLUGIN_LOGS_PATH . 'controllers/logs.php';
|
||||
if (function_exists('logs_plugin_handle')) {
|
||||
return logs_plugin_handle($action, $context);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
'access' => 'private',
|
||||
'defaults' => ['action' => 'list'],
|
||||
'plugin' => 'logs',
|
||||
]);
|
||||
```
|
||||
|
||||
## Hook + Loader API
|
||||
Core must fire the initialization hook after the database connection is ready:
|
||||
## Hook API
|
||||
Core must call:
|
||||
```php
|
||||
// After DB connect:
|
||||
do_hook('logger.system_init', ['db' => $db]);
|
||||
```
|
||||
The plugin listener:
|
||||
- calls `logs_ensure_tables()` to create the `log` table if needed
|
||||
- resolves the current user IP
|
||||
- exposes `$GLOBALS['logObject']` (`Log` instance) and `$GLOBALS['user_IP']`
|
||||
|
||||
When `$logObject` is not available, use `app_log($level, $message, $context)` which falls back to `NullLogger`.
|
||||
|
||||
## PHP API
|
||||
`Log` lives in `plugins/logs/models/Log.php` and receives the database connector.
|
||||
|
||||
### Methods
|
||||
The plugin listens on `logger.system_init`, runs auto-migration, then sets:
|
||||
```php
|
||||
Log::log(string $level, string $message, array $context = []): void
|
||||
Log::readLog(int $userId, string $scope, int $offset = 0, int $itemsPerPage = 0, array $filters = []): array
|
||||
$GLOBALS['logObject']; // instance of Log
|
||||
$GLOBALS['user_IP']; // current user IP
|
||||
```
|
||||
|
||||
### Supported log levels
|
||||
`emergency`, `alert`, `critical`, `error`, `warning`, `notice`, `info`, `debug`
|
||||
|
||||
### Supported filters
|
||||
- `from_time`: `YYYY-MM-DD` lower bound (inclusive)
|
||||
- `until_time`: `YYYY-MM-DD` upper bound (inclusive)
|
||||
- `message`: substring match across message text
|
||||
- `id`: explicit user ID (system scope only)
|
||||
|
||||
### Typical usage
|
||||
Then in the code use:
|
||||
```php
|
||||
app_log('info', 'User updated profile', [
|
||||
'user_id' => $userId,
|
||||
'scope' => 'user',
|
||||
]);
|
||||
|
||||
$entries = $logObject->readLog(
|
||||
$userId,
|
||||
$scope,
|
||||
$offset,
|
||||
$itemsPerPage,
|
||||
['message' => 'profile']
|
||||
);
|
||||
$logObject->insertLog($userId, 'Your message', 'user');
|
||||
$data = $logObject->readLog($userId, 'user', $offset, $limit, $filters);
|
||||
```
|
||||
|
||||
## Usage guidelines
|
||||
1. **When to log**
|
||||
- User actions, authentication events, configuration changes
|
||||
- System events, background job outcomes, and security anomalies
|
||||
2. **Message hygiene**
|
||||
- Keep messages concise, include essential metadata, avoid sensitive data
|
||||
3. **Data integrity**
|
||||
- Validate user input before logging to avoid malformed queries
|
||||
- Wrap bulk insertions in transactions when necessary
|
||||
4. **Performance**
|
||||
- Prefer pagination for large result sets
|
||||
- Index columns used by custom filters if extending the schema
|
||||
5. **Retention**
|
||||
- Schedule archival/log rotation via cron if the table grows quickly
|
||||
|
||||
## File Structure
|
||||
```
|
||||
plugins/logs/
|
||||
├─ bootstrap.php # registers route, migration function, hooks & menu
|
||||
├─ plugin.json # plugin metadata
|
||||
├─ README.md # this documentation
|
||||
├─ controllers/
|
||||
│ └─ logs.php # procedural handler functions for callable dispatcher
|
||||
plugins/logger/
|
||||
├─ bootstrap.php # registers hook
|
||||
├─ plugin.json # metadata & enabled flag
|
||||
├─ README.md # this documentation
|
||||
├─ models/
|
||||
│ ├─ Log.php # main Log class
|
||||
│ └─ LoggerFactory.php # migration + factory
|
||||
│ ├─ Log.php # main Log class
|
||||
│ └─ LoggerFactory.php# migration + factory
|
||||
├─ helpers/
|
||||
│ ├─ logs_view_helper.php
|
||||
├─ helpers.php # plugin helper wrapper
|
||||
│ └─ logs.php # user IP helper
|
||||
└─ migrations/
|
||||
└─ create_log_table.sql
|
||||
```
|
||||
|
||||
## Controller Architecture
|
||||
The controller uses procedural functions instead of classes:
|
||||
- `logs_plugin_handle($action, $context)` - main dispatcher function
|
||||
- `logs_plugin_render_list($logObject, $db, $userId, $validSession, $app_root)` - renders log list with filters and pagination
|
||||
|
||||
The callable dispatcher pattern provides:
|
||||
- Clean separation of concerns
|
||||
- Access to request context (user_id, db, app_root, valid_session)
|
||||
- Consistent error handling and layout rendering
|
||||
|
||||
## Admin Plugin Check
|
||||
The plugin provides `logs_ensure_tables()` for the admin plugin management interface:
|
||||
- **Owned tables:** `log` (will be removed on purge)
|
||||
- **Referenced tables:** `user` (dependency, not removed)
|
||||
|
||||
## Uninstall / Disable
|
||||
To disable the plugin:
|
||||
- Use the admin plugin management interface to disable it (updates the `settings` table), or
|
||||
- Delete the `plugins/logs/` folder entirely
|
||||
|
||||
When disabled, the `app_log()` helper automatically falls back to `NullLogger`, so logging calls remain safe and won't cause errors. To remove plugin data, use the admin plugin management interface to purge the `log` table.
|
||||
- Set `"enabled": false` in `plugin.json` or delete the `plugins/logger/` folder.
|
||||
- Core code will default to `NullLogger` and no logs will be written.
|
||||
|
|
|
|||
|
|
@ -1,63 +1,20 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Logs Plugin Bootstrap
|
||||
*
|
||||
* Initializes the logs plugin using the App API pattern.
|
||||
*/
|
||||
|
||||
// Logs plugin bootstrap
|
||||
if (!defined('PLUGIN_LOGS_PATH')) {
|
||||
define('PLUGIN_LOGS_PATH', __DIR__ . '/');
|
||||
}
|
||||
|
||||
// Load plugin helpers
|
||||
// We add the plugin helpers wrapper
|
||||
require_once PLUGIN_LOGS_PATH . 'helpers.php';
|
||||
|
||||
// Register route with callable dispatcher
|
||||
register_plugin_route_prefix('logs', [
|
||||
'dispatcher' => function($action, array $context = []) {
|
||||
require_once PLUGIN_LOGS_PATH . 'controllers/logs.php';
|
||||
if (function_exists('logs_plugin_handle')) {
|
||||
return logs_plugin_handle($action, $context);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
'access' => 'private',
|
||||
'defaults' => ['action' => 'list'],
|
||||
'plugin' => 'logs',
|
||||
]);
|
||||
|
||||
// Migration function for admin plugin check
|
||||
if (!function_exists('logs_ensure_tables')) {
|
||||
function logs_ensure_tables(): void {
|
||||
static $ensured = false;
|
||||
if ($ensured) {
|
||||
return;
|
||||
}
|
||||
$db = \App\App::db();
|
||||
if (!$db || !method_exists($db, 'getConnection')) {
|
||||
return;
|
||||
}
|
||||
$pdo = $db->getConnection();
|
||||
if (!$pdo instanceof \PDO) {
|
||||
return;
|
||||
}
|
||||
$migrationFile = __DIR__ . '/migrations/create_log_table.sql';
|
||||
if (is_readable($migrationFile)) {
|
||||
$sql = file_get_contents($migrationFile);
|
||||
if ($sql !== false && trim($sql) !== '') {
|
||||
$pdo->exec($sql);
|
||||
}
|
||||
}
|
||||
$ensured = true;
|
||||
}
|
||||
}
|
||||
// List here all the controllers in "/controllers/" that we need as pages
|
||||
$GLOBALS['plugin_controllers']['logs'] = [
|
||||
'logs'
|
||||
];
|
||||
|
||||
// Logger plugin bootstrap
|
||||
register_hook('logger.system_init', function(array $context) {
|
||||
// Ensure tables exist
|
||||
logs_ensure_tables();
|
||||
|
||||
// Load plugin-specific LoggerFactory class
|
||||
require_once __DIR__ . '/models/LoggerFactory.php';
|
||||
[$logger, $userIP] = LoggerFactory::create($context['db']);
|
||||
|
|
|
|||
|
|
@ -1,157 +1,122 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Logs Plugin Controller
|
||||
* Logs listings
|
||||
*
|
||||
* Procedural handler used by the callable dispatcher of the logs plugin.
|
||||
* This page ("logs") retrieves and displays logs within a time range
|
||||
* either for a specified user or for all users.
|
||||
* It supports pagination and filtering.
|
||||
*/
|
||||
|
||||
// Define plugin base path if not already defined
|
||||
if (!defined('PLUGIN_LOGS_PATH')) {
|
||||
define('PLUGIN_LOGS_PATH', dirname(__FILE__, 2) . '/');
|
||||
}
|
||||
require_once PLUGIN_LOGS_PATH . 'models/Log.php';
|
||||
require_once PLUGIN_LOGS_PATH . 'models/LoggerFactory.php';
|
||||
require_once APP_PATH . 'classes/user.php';
|
||||
require_once APP_PATH . 'helpers/theme.php';
|
||||
require_once dirname(__FILE__, 4) . '/app/classes/user.php';
|
||||
|
||||
function logs_plugin_handle(string $action, array $context = []): bool {
|
||||
$validSession = (bool)($context['valid_session'] ?? false);
|
||||
$app_root = $context['app_root'] ?? (\App\App::get('app_root') ?? '/');
|
||||
$db = $context['db'] ?? \App\App::db();
|
||||
$userId = $context['user_id'] ?? null;
|
||||
// Check for rights; user or system
|
||||
$has_system_access = ($userObject->hasRight($userId, 'superuser') ||
|
||||
$userObject->hasRight($userId, 'view app logs'));
|
||||
|
||||
if (!$db || !$userId) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Logs service unavailable.');
|
||||
header('Location: ' . $app_root);
|
||||
exit;
|
||||
}
|
||||
// Get current page for pagination
|
||||
$currentPage = $_REQUEST['page_num'] ?? 1;
|
||||
$currentPage = (int)$currentPage;
|
||||
|
||||
// Get logger instance from globals (set by logger.system_init hook)
|
||||
$logObject = $GLOBALS['logObject'] ?? null;
|
||||
if (!$logObject) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Logger not initialized.');
|
||||
header('Location: ' . $app_root);
|
||||
exit;
|
||||
}
|
||||
|
||||
switch ($action) {
|
||||
case 'list':
|
||||
default:
|
||||
logs_plugin_render_list($logObject, $db, $userId, $validSession, $app_root);
|
||||
return true;
|
||||
}
|
||||
// Get selected tab
|
||||
$selected_tab = $_REQUEST['tab'] ?? 'user';
|
||||
if ($selected_tab === 'system' && !$has_system_access) {
|
||||
$selected_tab = 'user';
|
||||
}
|
||||
|
||||
function logs_plugin_render_list($logObject, $db, int $userId, bool $validSession, string $app_root): void {
|
||||
// Load User class for permissions check
|
||||
$userObject = new \User($db);
|
||||
// Set scope based on selected tab
|
||||
$scope = ($selected_tab === 'system') ? 'system' : 'user';
|
||||
|
||||
// Check for rights; user or system
|
||||
$has_system_access = ($userObject->hasRight($userId, 'superuser') ||
|
||||
$userObject->hasRight($userId, 'view app logs'));
|
||||
// specify time range
|
||||
include '../app/helpers/time_range.php';
|
||||
|
||||
// Get current page for pagination
|
||||
$currentPage = $_REQUEST['page_num'] ?? 1;
|
||||
$currentPage = (int)$currentPage;
|
||||
// Prepare search filters
|
||||
$filters = [];
|
||||
if (isset($_REQUEST['from_time']) && !empty($_REQUEST['from_time'])) {
|
||||
$filters['from_time'] = $_REQUEST['from_time'];
|
||||
}
|
||||
if (isset($_REQUEST['until_time']) && !empty($_REQUEST['until_time'])) {
|
||||
$filters['until_time'] = $_REQUEST['until_time'];
|
||||
}
|
||||
if (isset($_REQUEST['message']) && !empty($_REQUEST['message'])) {
|
||||
$filters['message'] = $_REQUEST['message'];
|
||||
}
|
||||
if ($scope === 'system' && isset($_REQUEST['id']) && !empty($_REQUEST['id'])) {
|
||||
$filters['id'] = $_REQUEST['id'];
|
||||
}
|
||||
|
||||
// Get selected tab
|
||||
$selected_tab = $_REQUEST['tab'] ?? 'user';
|
||||
if ($selected_tab === 'system' && !$has_system_access) {
|
||||
$selected_tab = 'user';
|
||||
}
|
||||
// pagination variables
|
||||
$items_per_page = 15;
|
||||
$offset = ($currentPage - 1) * $items_per_page;
|
||||
|
||||
// Set scope based on selected tab
|
||||
$scope = ($selected_tab === 'system') ? 'system' : 'user';
|
||||
// Build params for pagination
|
||||
$params = '';
|
||||
if (!empty($_REQUEST['from_time'])) {
|
||||
$params .= '&from_time=' . urlencode($_REQUEST['from_time']);
|
||||
}
|
||||
if (!empty($_REQUEST['until_time'])) {
|
||||
$params .= '&until_time=' . urlencode($_REQUEST['until_time']);
|
||||
}
|
||||
if (!empty($_REQUEST['message'])) {
|
||||
$params .= '&message=' . urlencode($_REQUEST['message']);
|
||||
}
|
||||
if (!empty($_REQUEST['id'])) {
|
||||
$params .= '&id=' . urlencode($_REQUEST['id']);
|
||||
}
|
||||
if (isset($_REQUEST['tab'])) {
|
||||
$params .= '&tab=' . urlencode($_REQUEST['tab']);
|
||||
}
|
||||
|
||||
// Specify time range
|
||||
include APP_PATH . 'helpers/time_range.php';
|
||||
// prepare the result
|
||||
$search = $logObject->readLog($userId, $scope, $offset, $items_per_page, $filters);
|
||||
$search_all = $logObject->readLog($userId, $scope, 0, 0, $filters);
|
||||
|
||||
// Prepare search filters
|
||||
$filters = [];
|
||||
if (isset($_REQUEST['from_time']) && !empty($_REQUEST['from_time'])) {
|
||||
$filters['from_time'] = $_REQUEST['from_time'];
|
||||
}
|
||||
if (isset($_REQUEST['until_time']) && !empty($_REQUEST['until_time'])) {
|
||||
$filters['until_time'] = $_REQUEST['until_time'];
|
||||
}
|
||||
if (isset($_REQUEST['message']) && !empty($_REQUEST['message'])) {
|
||||
$filters['message'] = $_REQUEST['message'];
|
||||
}
|
||||
if ($scope === 'system' && isset($_REQUEST['id']) && !empty($_REQUEST['id'])) {
|
||||
$filters['id'] = $_REQUEST['id'];
|
||||
}
|
||||
if (!empty($search)) {
|
||||
// we get total items and number of pages
|
||||
$item_count = count($search_all);
|
||||
$totalPages = ceil($item_count / $items_per_page);
|
||||
|
||||
// Pagination variables
|
||||
$items_per_page = 15;
|
||||
$offset = ($currentPage - 1) * $items_per_page;
|
||||
$logs = array();
|
||||
$logs['records'] = array();
|
||||
|
||||
// Build params for pagination
|
||||
$params = '';
|
||||
if (!empty($_REQUEST['from_time'])) {
|
||||
$params .= '&from_time=' . urlencode($_REQUEST['from_time']);
|
||||
}
|
||||
if (!empty($_REQUEST['until_time'])) {
|
||||
$params .= '&until_time=' . urlencode($_REQUEST['until_time']);
|
||||
}
|
||||
if (!empty($_REQUEST['message'])) {
|
||||
$params .= '&message=' . urlencode($_REQUEST['message']);
|
||||
}
|
||||
if (!empty($_REQUEST['id'])) {
|
||||
$params .= '&id=' . urlencode($_REQUEST['id']);
|
||||
}
|
||||
if (isset($_REQUEST['tab'])) {
|
||||
$params .= '&tab=' . urlencode($_REQUEST['tab']);
|
||||
}
|
||||
|
||||
// Prepare the result
|
||||
$search = $logObject->readLog($userId, $scope, $offset, $items_per_page, $filters);
|
||||
$search_all = $logObject->readLog($userId, $scope, 0, 0, $filters);
|
||||
|
||||
$logs = [];
|
||||
$totalPages = 0;
|
||||
$item_count = 0;
|
||||
|
||||
if (!empty($search)) {
|
||||
// Get total items and number of pages
|
||||
$item_count = count($search_all);
|
||||
$totalPages = ceil($item_count / $items_per_page);
|
||||
|
||||
$logs = [];
|
||||
$logs['records'] = [];
|
||||
|
||||
foreach ($search as $item) {
|
||||
// When we show only user's logs, omit user_id column
|
||||
if ($scope === 'user') {
|
||||
// assign title to the field
|
||||
$log_record = [
|
||||
'time' => $item['time'],
|
||||
'log level' => $item['level'],
|
||||
'log message' => $item['message']
|
||||
];
|
||||
} else {
|
||||
// assign title to the field
|
||||
$log_record = [
|
||||
'userID' => $item['user_id'],
|
||||
'username' => $item['username'],
|
||||
'time' => $item['time'],
|
||||
'log level' => $item['level'],
|
||||
'log message' => $item['message']
|
||||
];
|
||||
}
|
||||
|
||||
$logs['records'][] = $log_record;
|
||||
foreach ($search as $item) {
|
||||
// when we show only user's logs, omit user_id column
|
||||
if ($scope === 'user') {
|
||||
$log_record = array(
|
||||
// assign title to the field in the array record
|
||||
'time' => $item['time'],
|
||||
'log level' => $item['level'],
|
||||
'log message' => $item['message']
|
||||
);
|
||||
} else {
|
||||
$log_record = array(
|
||||
// assign title to the field in the array record
|
||||
'userID' => $item['user_id'],
|
||||
'username' => $item['username'],
|
||||
'time' => $item['time'],
|
||||
'log level' => $item['level'],
|
||||
'log message' => $item['message']
|
||||
);
|
||||
}
|
||||
|
||||
// populate the result array
|
||||
array_push($logs['records'], $log_record);
|
||||
}
|
||||
|
||||
$username = $userObject->getUserDetails($userId)[0]['username'];
|
||||
$page = 'logs'; // For pagination template
|
||||
|
||||
\App\Helpers\Theme::include('page-header');
|
||||
\App\Helpers\Theme::include('page-menu');
|
||||
if ($validSession) {
|
||||
\App\Helpers\Theme::include('page-sidebar');
|
||||
}
|
||||
|
||||
include APP_PATH . 'helpers/feedback.php';
|
||||
require_once PLUGIN_LOGS_PATH . 'helpers/logs_view_helper.php';
|
||||
include PLUGIN_LOGS_PATH . 'views/logs.php';
|
||||
|
||||
\App\Helpers\Theme::include('page-footer');
|
||||
}
|
||||
|
||||
$username = $userObject->getUserDetails($userId)[0]['username'];
|
||||
|
||||
// Get any new feedback messages
|
||||
include_once dirname(__FILE__, 4) . '/app/helpers/feedback.php';
|
||||
|
||||
// Load plugin helpers
|
||||
require_once PLUGIN_LOGS_PATH . 'helpers/logs_view_helper.php';
|
||||
|
||||
// Display messages list
|
||||
include PLUGIN_LOGS_PATH . 'views/logs.php';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "Logger Plugin",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.1",
|
||||
"description": "Initializes logging system via LoggerFactory"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,55 +44,16 @@ Enable/disable registration in `totalmeet.conf.php`:
|
|||
|
||||
## Implementation
|
||||
|
||||
Uses callable dispatcher pattern with procedural handler functions:
|
||||
Uses simple callable dispatcher pattern for single-action plugin:
|
||||
```php
|
||||
register_plugin_route_prefix('register', [
|
||||
'dispatcher' => function($action, array $context = []) {
|
||||
'dispatcher' => function($context) {
|
||||
require_once PLUGIN_REGISTER_PATH . 'controllers/register.php';
|
||||
if (function_exists('register_plugin_handle_register')) {
|
||||
return register_plugin_handle_register($action, $context);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
'access' => 'public',
|
||||
'defaults' => ['action' => 'register'],
|
||||
'plugin' => 'register',
|
||||
]);
|
||||
```
|
||||
|
||||
## Controller Architecture
|
||||
|
||||
The controller uses procedural functions:
|
||||
- `register_plugin_handle_register($action, $context)` - main handler
|
||||
- `register_plugin_handle_submission(...)` - processes form submission
|
||||
- `register_plugin_render_form(...)` - renders registration form with layout
|
||||
- `register_plugin_log_success(...)` - logs successful registration
|
||||
|
||||
## Database Tables
|
||||
|
||||
No plugin-specific tables. Uses core `user` and `user_meta` tables.
|
||||
|
||||
## Enable/Disable
|
||||
|
||||
The plugin is managed via the admin plugin management interface (stored in `settings` table).
|
||||
When disabled, the registration route becomes unavailable.
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
plugins/register/
|
||||
├── bootstrap.php # registers route with callable dispatcher
|
||||
├── plugin.json # plugin metadata
|
||||
├── README.md # this documentation
|
||||
├── controllers/
|
||||
│ └── register.php # procedural handler functions
|
||||
├── models/
|
||||
│ └── register.php # registration logic and validation
|
||||
├── helpers.php # plugin helper wrapper
|
||||
└── views/
|
||||
└── form-register.php # registration form template
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
None - functions independently.
|
||||
|
|
|
|||
|
|
@ -12,16 +12,11 @@ if (!defined('PLUGIN_REGISTER_PATH')) {
|
|||
}
|
||||
|
||||
require_once PLUGIN_REGISTER_PATH . 'helpers.php';
|
||||
require_once PLUGIN_REGISTER_PATH . 'controllers/register.php';
|
||||
|
||||
// Register route with simple callable dispatcher
|
||||
// Register route with dispatcher class
|
||||
register_plugin_route_prefix('register', [
|
||||
'dispatcher' => function($action, array $context = []) {
|
||||
require_once PLUGIN_REGISTER_PATH . 'controllers/register.php';
|
||||
if (function_exists('register_plugin_handle_register')) {
|
||||
return register_plugin_handle_register($action, $context);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
'dispatcher' => \Plugins\Register\Controllers\RegisterController::class,
|
||||
'access' => 'public',
|
||||
'defaults' => ['action' => 'register'],
|
||||
'plugin' => 'register',
|
||||
|
|
|
|||
|
|
@ -1,11 +1,19 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Register Plugin Controller
|
||||
* User Registration API Controller
|
||||
*
|
||||
* Procedural handler used by the callable dispatcher.
|
||||
* Provides RESTful endpoints for user registration.
|
||||
* Follows the API pattern used by other plugins.
|
||||
*/
|
||||
|
||||
namespace Plugins\Register\Controllers;
|
||||
|
||||
use App\App;
|
||||
use App\Helpers\Theme;
|
||||
use Exception;
|
||||
use PDO;
|
||||
|
||||
require_once APP_PATH . 'classes/feedback.php';
|
||||
require_once APP_PATH . 'classes/user.php';
|
||||
require_once APP_PATH . 'classes/validator.php';
|
||||
|
|
@ -14,146 +22,167 @@ require_once APP_PATH . 'helpers/theme.php';
|
|||
require_once APP_PATH . 'includes/rate_limit_middleware.php';
|
||||
require_once PLUGIN_REGISTER_PATH . 'models/register.php';
|
||||
|
||||
function register_plugin_handle_register(string $action, array $context = []): bool {
|
||||
$validSession = (bool)($context['valid_session'] ?? false);
|
||||
$app_root = $context['app_root'] ?? (\App\App::get('app_root') ?? '/');
|
||||
$config = $context['config'] ?? \App\App::config();
|
||||
$db = $context['db'] ?? \App\App::db();
|
||||
$logger = $context['logger'] ?? \App\App::get('logger');
|
||||
class RegisterController
|
||||
{
|
||||
private $db;
|
||||
private array $config;
|
||||
private string $appRoot;
|
||||
private $logger;
|
||||
|
||||
if (!$db) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration service unavailable. Please try again later.');
|
||||
register_plugin_render_form($validSession, $app_root, ['registrationEnabled' => false]);
|
||||
return true;
|
||||
public function __construct()
|
||||
{
|
||||
$this->db = App::db();
|
||||
$this->config = App::config();
|
||||
$this->appRoot = App::get('app_root') ?? '/';
|
||||
$this->logger = App::get('logObject');
|
||||
}
|
||||
|
||||
if (!(bool)($config['registration_enabled'] ?? false)) {
|
||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration is currently disabled.');
|
||||
register_plugin_render_form($validSession, $app_root, ['registrationEnabled' => false]);
|
||||
return true;
|
||||
}
|
||||
public function handle(string $action, array $context = []): bool
|
||||
{
|
||||
$validSession = (bool)($context['valid_session'] ?? false);
|
||||
$app_root = $context['app_root'] ?? $this->appRoot;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
register_plugin_handle_submission($validSession, $app_root, $db, $logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
register_plugin_render_form($validSession, $app_root);
|
||||
return true;
|
||||
}
|
||||
|
||||
function register_plugin_handle_submission(bool $validSession, string $app_root, $db, $logger = null): void {
|
||||
checkRateLimit($db, 'register');
|
||||
|
||||
$security = \SecurityHelper::getInstance();
|
||||
$formData = $security->sanitizeArray(
|
||||
$_POST,
|
||||
['username', 'password', 'confirm_password', 'csrf_token', 'terms']
|
||||
);
|
||||
|
||||
if (!$security->verifyCsrfToken($formData['csrf_token'] ?? '')) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Invalid security token. Please try again.');
|
||||
register_plugin_render_form($validSession, $app_root, [
|
||||
'values' => ['username' => $formData['username'] ?? ''],
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$validator = new \Validator($formData);
|
||||
$rules = [
|
||||
'username' => [
|
||||
'required' => true,
|
||||
'min' => 3,
|
||||
'max' => 20,
|
||||
],
|
||||
'password' => [
|
||||
'required' => true,
|
||||
'min' => 8,
|
||||
'max' => 255,
|
||||
],
|
||||
'confirm_password' => [
|
||||
'required' => true,
|
||||
'matches' => 'password',
|
||||
],
|
||||
'terms' => [
|
||||
'required' => true,
|
||||
'accepted' => true,
|
||||
],
|
||||
];
|
||||
|
||||
if (!$validator->validate($rules)) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', $validator->getFirstError());
|
||||
register_plugin_render_form($validSession, $app_root, [
|
||||
'values' => ['username' => $formData['username'] ?? ''],
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$username = trim($formData['username']);
|
||||
$password = $formData['password'];
|
||||
|
||||
$pdo = $db instanceof \PDO ? $db : $db->getConnection();
|
||||
|
||||
try {
|
||||
$register = new \Register($pdo);
|
||||
$result = $register->register($username, $password);
|
||||
|
||||
if ($result === true) {
|
||||
register_plugin_log_success($username, $db, $logger);
|
||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration successful. You can log in now.');
|
||||
header('Location: ' . $app_root . '?page=login');
|
||||
exit;
|
||||
if (!$this->db) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration service unavailable. Please try again later.');
|
||||
$this->renderForm($validSession, $app_root, ['registrationEnabled' => false]);
|
||||
return true;
|
||||
}
|
||||
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $result);
|
||||
register_plugin_render_form($validSession, $app_root, [
|
||||
'values' => ['username' => $username],
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $e->getMessage());
|
||||
register_plugin_render_form($validSession, $app_root, [
|
||||
'values' => ['username' => $username],
|
||||
]);
|
||||
}
|
||||
}
|
||||
if (!$this->isRegistrationEnabled()) {
|
||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration is currently disabled.');
|
||||
$this->renderForm($validSession, $app_root, ['registrationEnabled' => false]);
|
||||
return true;
|
||||
}
|
||||
|
||||
function register_plugin_log_success(string $username, $db, $logger = null): void {
|
||||
if (!$logger) {
|
||||
return;
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$this->handleSubmission($validSession, $app_root);
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->renderForm($validSession, $app_root);
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
$userModel = new \User($db);
|
||||
$userRecord = $userModel->getUserId($username);
|
||||
$userId = $userRecord[0]['id'] ?? null;
|
||||
$userIP = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
private function isRegistrationEnabled(): bool
|
||||
{
|
||||
return (bool)($this->config['registration_enabled'] ?? false);
|
||||
}
|
||||
|
||||
$logger->log(
|
||||
'info',
|
||||
sprintf('Registration: New user "%s" registered successfully. IP: %s', $username, $userIP),
|
||||
['user_id' => $userId, 'scope' => 'user']
|
||||
private function handleSubmission(bool $validSession, string $app_root): void
|
||||
{
|
||||
checkRateLimit($this->db, 'register');
|
||||
|
||||
$security = \SecurityHelper::getInstance();
|
||||
$formData = $security->sanitizeArray(
|
||||
$_POST,
|
||||
['username', 'password', 'confirm_password', 'csrf_token', 'terms']
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
app_log('warning', 'Register plugin logging failed: ' . $e->getMessage(), ['scope' => 'plugin']);
|
||||
}
|
||||
}
|
||||
|
||||
function register_plugin_render_form(bool $validSession, string $app_root, array $data = []): void {
|
||||
$formValues = $data['values'] ?? ['username' => ''];
|
||||
$registrationEnabled = $data['registrationEnabled'] ?? true;
|
||||
if (!$security->verifyCsrfToken($formData['csrf_token'] ?? '')) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Invalid security token. Please try again.');
|
||||
$this->renderForm($validSession, $app_root, [
|
||||
'values' => ['username' => $formData['username'] ?? ''],
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
\App\Helpers\Theme::include('page-header');
|
||||
\App\Helpers\Theme::include('page-menu');
|
||||
if ($validSession) {
|
||||
\App\Helpers\Theme::include('page-sidebar');
|
||||
$validator = new \Validator($formData);
|
||||
$rules = [
|
||||
'username' => [
|
||||
'required' => true,
|
||||
'min' => 3,
|
||||
'max' => 20,
|
||||
],
|
||||
'password' => [
|
||||
'required' => true,
|
||||
'min' => 8,
|
||||
'max' => 255,
|
||||
],
|
||||
'confirm_password' => [
|
||||
'required' => true,
|
||||
'matches' => 'password',
|
||||
],
|
||||
'terms' => [
|
||||
'required' => true,
|
||||
'accepted' => true,
|
||||
],
|
||||
];
|
||||
|
||||
if (!$validator->validate($rules)) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', $validator->getFirstError());
|
||||
$this->renderForm($validSession, $app_root, [
|
||||
'values' => ['username' => $formData['username'] ?? ''],
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$username = trim($formData['username']);
|
||||
$password = $formData['password'];
|
||||
|
||||
try {
|
||||
$register = new \Register($this->db);
|
||||
$result = $register->register($username, $password);
|
||||
|
||||
if ($result === true) {
|
||||
$this->logSuccessfulRegistration($username);
|
||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration successful. You can log in now.');
|
||||
header('Location: ' . $app_root . '?page=login');
|
||||
exit;
|
||||
}
|
||||
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $result);
|
||||
$this->renderForm($validSession, $app_root, [
|
||||
'values' => ['username' => $username],
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $e->getMessage());
|
||||
$this->renderForm($validSession, $app_root, [
|
||||
'values' => ['username' => $username],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
include APP_PATH . 'helpers/feedback.php';
|
||||
private function logSuccessfulRegistration(string $username): void
|
||||
{
|
||||
if (!$this->logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
$values = $formValues;
|
||||
$app_root = $app_root;
|
||||
try {
|
||||
$userModel = new \User($this->db);
|
||||
$userRecord = $userModel->getUserId($username);
|
||||
$userId = $userRecord[0]['id'] ?? null;
|
||||
$userIP = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
|
||||
include PLUGIN_REGISTER_PATH . 'views/form-register.php';
|
||||
$this->logger->log(
|
||||
'info',
|
||||
sprintf('Registration: New user "%s" registered successfully. IP: %s', $username, $userIP),
|
||||
['user_id' => $userId, 'scope' => 'user']
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
app_log('warning', 'RegisterController logging failed: ' . $e->getMessage(), ['scope' => 'plugin']);
|
||||
}
|
||||
}
|
||||
|
||||
\App\Helpers\Theme::include('page-footer');
|
||||
private function renderForm(bool $validSession, string $app_root, array $data = []): void
|
||||
{
|
||||
$formValues = $data['values'] ?? ['username' => ''];
|
||||
$registrationEnabled = $data['registrationEnabled'] ?? true;
|
||||
|
||||
Theme::include('page-header');
|
||||
Theme::include('page-menu');
|
||||
if ($validSession) {
|
||||
Theme::include('page-sidebar');
|
||||
}
|
||||
|
||||
include APP_PATH . 'helpers/feedback.php';
|
||||
|
||||
$app_root_value = $app_root; // align variable name for template include
|
||||
$app_root = $app_root_value;
|
||||
$values = $formValues;
|
||||
|
||||
include PLUGIN_REGISTER_PATH . 'views/form-register.php';
|
||||
|
||||
Theme::include('page-footer');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "Registration Plugin",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.1",
|
||||
"description": "Provides registration functionality as a plugin."
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue