Compare commits
4 Commits
d318b621d5
...
eb4b5ca7bc
| Author | SHA1 | Date |
|---|---|---|
|
|
eb4b5ca7bc | |
|
|
58c2651796 | |
|
|
80aaa0cab6 | |
|
|
4c5136adf4 |
|
|
@ -603,25 +603,41 @@ if ($queryAction === 'plugin_check_page' && isset($_GET['plugin'])) {
|
||||||
|
|
||||||
// Check database tables
|
// Check database tables
|
||||||
$db = \App\App::db();
|
$db = \App\App::db();
|
||||||
$pluginTables = [];
|
$pluginOwnedTables = [];
|
||||||
if ($db instanceof PDO) {
|
$pluginReferencedTables = [];
|
||||||
$stmt = $db->query("SHOW TABLES");
|
if ($db && method_exists($db, 'getConnection')) {
|
||||||
|
$pdo = $db->getConnection();
|
||||||
|
$stmt = $pdo->query("SHOW TABLES");
|
||||||
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
||||||
|
|
||||||
if ($hasMigration) {
|
if ($hasMigration) {
|
||||||
// Check each migration file for table references
|
|
||||||
foreach ($migrationFiles as $migrationFile) {
|
foreach ($migrationFiles as $migrationFile) {
|
||||||
$migrationContent = file_get_contents($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) {
|
foreach ($allTables as $table) {
|
||||||
if (strpos($migrationContent, $table) !== false) {
|
if (strpos($migrationContent, $table) !== false && !in_array($table, $pluginOwnedTables)) {
|
||||||
$pluginTables[] = $table;
|
$pluginReferencedTables[] = $table;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$pluginTables = array_unique($pluginTables);
|
$pluginOwnedTables = array_unique($pluginOwnedTables);
|
||||||
|
$pluginReferencedTables = array_unique($pluginReferencedTables);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$checkResults['tables'] = $pluginTables;
|
$checkResults['tables'] = [
|
||||||
|
'owned' => $pluginOwnedTables,
|
||||||
|
'referenced' => $pluginReferencedTables,
|
||||||
|
];
|
||||||
|
|
||||||
// Check plugin functions
|
// Check plugin functions
|
||||||
$bootstrapPath = $pluginInfo['path'] . '/bootstrap.php';
|
$bootstrapPath = $pluginInfo['path'] . '/bootstrap.php';
|
||||||
|
|
|
||||||
|
|
@ -628,25 +628,41 @@ endif; ?>
|
||||||
|
|
||||||
// Check database tables
|
// Check database tables
|
||||||
$db = \App\App::db();
|
$db = \App\App::db();
|
||||||
$pluginTables = [];
|
$pluginOwnedTables = [];
|
||||||
if ($db instanceof PDO) {
|
$pluginReferencedTables = [];
|
||||||
$stmt = $db->query("SHOW TABLES");
|
if ($db && method_exists($db, 'getConnection')) {
|
||||||
|
$pdo = $db->getConnection();
|
||||||
|
$stmt = $pdo->query("SHOW TABLES");
|
||||||
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
$allTables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
|
||||||
|
|
||||||
if ($hasMigration) {
|
if ($hasMigration) {
|
||||||
// Check each migration file for table references
|
|
||||||
foreach ($migrationFiles as $migrationFile) {
|
foreach ($migrationFiles as $migrationFile) {
|
||||||
$migrationContent = file_get_contents($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) {
|
foreach ($allTables as $table) {
|
||||||
if (strpos($migrationContent, $table) !== false) {
|
if (strpos($migrationContent, $table) !== false && !in_array($table, $pluginOwnedTables)) {
|
||||||
$pluginTables[] = $table;
|
$pluginReferencedTables[] = $table;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$pluginTables = array_unique($pluginTables);
|
$pluginOwnedTables = array_unique($pluginOwnedTables);
|
||||||
|
$pluginReferencedTables = array_unique($pluginReferencedTables);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$checkResults['tables'] = $pluginTables;
|
$checkResults['tables'] = [
|
||||||
|
'owned' => $pluginOwnedTables,
|
||||||
|
'referenced' => $pluginReferencedTables,
|
||||||
|
];
|
||||||
|
|
||||||
// Check plugin functions and integrations
|
// Check plugin functions and integrations
|
||||||
$bootstrapPath = $plugin['path'] . '/bootstrap.php';
|
$bootstrapPath = $plugin['path'] . '/bootstrap.php';
|
||||||
|
|
@ -773,13 +789,29 @@ endif; ?>
|
||||||
<h6 class="card-title mb-0">Database Tables</h6>
|
<h6 class="card-title mb-0">Database Tables</h6>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<?php if (!empty($checkResults['tables'])): ?>
|
<?php if (!empty($checkResults['tables']['owned']) || !empty($checkResults['tables']['referenced'])): ?>
|
||||||
<?php foreach ($checkResults['tables'] as $table): ?>
|
<?php if (!empty($checkResults['tables']['owned'])): ?>
|
||||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
<div class="mb-3">
|
||||||
<span><?= htmlspecialchars($table) ?></span>
|
<strong class="text-danger">Plugin Tables (removed on purge):</strong>
|
||||||
<span class="badge bg-success">Present</span>
|
<?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>
|
</div>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
|
</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 else: ?>
|
<?php else: ?>
|
||||||
<p class="text-muted mb-0">
|
<p class="text-muted mb-0">
|
||||||
<?php if ($checkResults['files']['migration']): ?>
|
<?php if ($checkResults['files']['migration']): ?>
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,38 @@
|
||||||
# Logger plugin
|
# Logger plugin
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
The Logger plugin provides a modular, pluggable logging system for the application.
|
The Logger plugin (located in `plugins/logs/`) provides a modular, pluggable logging
|
||||||
It logs user and system events to a MySQL table named `log`.
|
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
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
1. Copy the entire `logger` folder into your project's `plugins/` directory.
|
1. Copy the `logs` folder into the project's `plugins/` directory.
|
||||||
2. Ensure `"enabled": true` in `plugins/logger/plugin.json`.
|
2. Enable the plugin via the admin plugin management interface (stored in `settings` table).
|
||||||
3. On first initialization, the plugin will create the `log` table if it does not already exist.
|
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
|
||||||
|
|
||||||
## Database Schema
|
## Database Schema
|
||||||
The plugin defines the following table (auto-created):
|
The plugin defines the following table (auto-created):
|
||||||
|
|
@ -24,39 +49,120 @@ CREATE TABLE IF NOT EXISTS `log` (
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Hook API
|
## Routing & Dispatcher
|
||||||
Core must call:
|
The plugin registers its route using `PluginRouteRegistry`:
|
||||||
```php
|
```php
|
||||||
// After DB connect:
|
register_plugin_route_prefix('logs', [
|
||||||
do_hook('logger.system_init', ['db' => $db]);
|
'dispatcher' => function($action, array $context = []) {
|
||||||
```
|
require_once PLUGIN_LOGS_PATH . 'controllers/logs.php';
|
||||||
The plugin listens on `logger.system_init`, runs auto-migration, then sets:
|
if (function_exists('logs_plugin_handle')) {
|
||||||
```php
|
return logs_plugin_handle($action, $context);
|
||||||
$GLOBALS['logObject']; // instance of Log
|
}
|
||||||
$GLOBALS['user_IP']; // current user IP
|
return false;
|
||||||
|
},
|
||||||
|
'access' => 'private',
|
||||||
|
'defaults' => ['action' => 'list'],
|
||||||
|
'plugin' => 'logs',
|
||||||
|
]);
|
||||||
```
|
```
|
||||||
|
|
||||||
Then in the code use:
|
## Hook + Loader API
|
||||||
|
Core must fire the initialization hook after the database connection is ready:
|
||||||
```php
|
```php
|
||||||
$logObject->insertLog($userId, 'Your message', 'user');
|
do_hook('logger.system_init', ['db' => $db]);
|
||||||
$data = $logObject->readLog($userId, 'user', $offset, $limit, $filters);
|
|
||||||
```
|
```
|
||||||
|
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
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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
|
||||||
|
```php
|
||||||
|
app_log('info', 'User updated profile', [
|
||||||
|
'user_id' => $userId,
|
||||||
|
'scope' => 'user',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$entries = $logObject->readLog(
|
||||||
|
$userId,
|
||||||
|
$scope,
|
||||||
|
$offset,
|
||||||
|
$itemsPerPage,
|
||||||
|
['message' => 'profile']
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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
|
## File Structure
|
||||||
```
|
```
|
||||||
plugins/logger/
|
plugins/logs/
|
||||||
├─ bootstrap.php # registers hook
|
├─ bootstrap.php # registers route, migration function, hooks & menu
|
||||||
├─ plugin.json # metadata & enabled flag
|
├─ plugin.json # plugin metadata
|
||||||
├─ README.md # this documentation
|
├─ README.md # this documentation
|
||||||
|
├─ controllers/
|
||||||
|
│ └─ logs.php # procedural handler functions for callable dispatcher
|
||||||
├─ models/
|
├─ models/
|
||||||
│ ├─ Log.php # main Log class
|
│ ├─ Log.php # main Log class
|
||||||
│ └─ LoggerFactory.php # migration + factory
|
│ └─ LoggerFactory.php # migration + factory
|
||||||
├─ helpers/
|
├─ helpers/
|
||||||
│ └─ logs.php # user IP helper
|
│ ├─ logs_view_helper.php
|
||||||
|
├─ helpers.php # plugin helper wrapper
|
||||||
└─ migrations/
|
└─ migrations/
|
||||||
└─ create_log_table.sql
|
└─ 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
|
## Uninstall / Disable
|
||||||
- Set `"enabled": false` in `plugin.json` or delete the `plugins/logger/` folder.
|
To disable the plugin:
|
||||||
- Core code will default to `NullLogger` and no logs will be written.
|
- 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.
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,63 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
// Logs plugin bootstrap
|
/**
|
||||||
|
* Logs Plugin Bootstrap
|
||||||
|
*
|
||||||
|
* Initializes the logs plugin using the App API pattern.
|
||||||
|
*/
|
||||||
|
|
||||||
if (!defined('PLUGIN_LOGS_PATH')) {
|
if (!defined('PLUGIN_LOGS_PATH')) {
|
||||||
define('PLUGIN_LOGS_PATH', __DIR__ . '/');
|
define('PLUGIN_LOGS_PATH', __DIR__ . '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
// We add the plugin helpers wrapper
|
// Load plugin helpers
|
||||||
require_once PLUGIN_LOGS_PATH . 'helpers.php';
|
require_once PLUGIN_LOGS_PATH . 'helpers.php';
|
||||||
|
|
||||||
// List here all the controllers in "/controllers/" that we need as pages
|
// Register route with callable dispatcher
|
||||||
$GLOBALS['plugin_controllers']['logs'] = [
|
register_plugin_route_prefix('logs', [
|
||||||
'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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Logger plugin bootstrap
|
// Logger plugin bootstrap
|
||||||
register_hook('logger.system_init', function(array $context) {
|
register_hook('logger.system_init', function(array $context) {
|
||||||
|
// Ensure tables exist
|
||||||
|
logs_ensure_tables();
|
||||||
|
|
||||||
// Load plugin-specific LoggerFactory class
|
// Load plugin-specific LoggerFactory class
|
||||||
require_once __DIR__ . '/models/LoggerFactory.php';
|
require_once __DIR__ . '/models/LoggerFactory.php';
|
||||||
[$logger, $userIP] = LoggerFactory::create($context['db']);
|
[$logger, $userIP] = LoggerFactory::create($context['db']);
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,47 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs listings
|
* Logs Plugin Controller
|
||||||
*
|
*
|
||||||
* This page ("logs") retrieves and displays logs within a time range
|
* Procedural handler used by the callable dispatcher of the logs plugin.
|
||||||
* 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/Log.php';
|
||||||
require_once PLUGIN_LOGS_PATH . 'models/LoggerFactory.php';
|
require_once PLUGIN_LOGS_PATH . 'models/LoggerFactory.php';
|
||||||
require_once dirname(__FILE__, 4) . '/app/classes/user.php';
|
require_once APP_PATH . 'classes/user.php';
|
||||||
|
require_once APP_PATH . 'helpers/theme.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;
|
||||||
|
|
||||||
|
if (!$db || !$userId) {
|
||||||
|
\Feedback::flash('ERROR', 'DEFAULT', 'Logs service unavailable.');
|
||||||
|
header('Location: ' . $app_root);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
// Check for rights; user or system
|
// Check for rights; user or system
|
||||||
$has_system_access = ($userObject->hasRight($userId, 'superuser') ||
|
$has_system_access = ($userObject->hasRight($userId, 'superuser') ||
|
||||||
|
|
@ -33,8 +60,8 @@ if ($selected_tab === 'system' && !$has_system_access) {
|
||||||
// Set scope based on selected tab
|
// Set scope based on selected tab
|
||||||
$scope = ($selected_tab === 'system') ? 'system' : 'user';
|
$scope = ($selected_tab === 'system') ? 'system' : 'user';
|
||||||
|
|
||||||
// specify time range
|
// Specify time range
|
||||||
include '../app/helpers/time_range.php';
|
include APP_PATH . 'helpers/time_range.php';
|
||||||
|
|
||||||
// Prepare search filters
|
// Prepare search filters
|
||||||
$filters = [];
|
$filters = [];
|
||||||
|
|
@ -51,7 +78,7 @@ if ($scope === 'system' && isset($_REQUEST['id']) && !empty($_REQUEST['id'])) {
|
||||||
$filters['id'] = $_REQUEST['id'];
|
$filters['id'] = $_REQUEST['id'];
|
||||||
}
|
}
|
||||||
|
|
||||||
// pagination variables
|
// Pagination variables
|
||||||
$items_per_page = 15;
|
$items_per_page = 15;
|
||||||
$offset = ($currentPage - 1) * $items_per_page;
|
$offset = ($currentPage - 1) * $items_per_page;
|
||||||
|
|
||||||
|
|
@ -73,50 +100,58 @@ if (isset($_REQUEST['tab'])) {
|
||||||
$params .= '&tab=' . urlencode($_REQUEST['tab']);
|
$params .= '&tab=' . urlencode($_REQUEST['tab']);
|
||||||
}
|
}
|
||||||
|
|
||||||
// prepare the result
|
// Prepare the result
|
||||||
$search = $logObject->readLog($userId, $scope, $offset, $items_per_page, $filters);
|
$search = $logObject->readLog($userId, $scope, $offset, $items_per_page, $filters);
|
||||||
$search_all = $logObject->readLog($userId, $scope, 0, 0, $filters);
|
$search_all = $logObject->readLog($userId, $scope, 0, 0, $filters);
|
||||||
|
|
||||||
|
$logs = [];
|
||||||
|
$totalPages = 0;
|
||||||
|
$item_count = 0;
|
||||||
|
|
||||||
if (!empty($search)) {
|
if (!empty($search)) {
|
||||||
// we get total items and number of pages
|
// Get total items and number of pages
|
||||||
$item_count = count($search_all);
|
$item_count = count($search_all);
|
||||||
$totalPages = ceil($item_count / $items_per_page);
|
$totalPages = ceil($item_count / $items_per_page);
|
||||||
|
|
||||||
$logs = array();
|
$logs = [];
|
||||||
$logs['records'] = array();
|
$logs['records'] = [];
|
||||||
|
|
||||||
foreach ($search as $item) {
|
foreach ($search as $item) {
|
||||||
// when we show only user's logs, omit user_id column
|
// When we show only user's logs, omit user_id column
|
||||||
if ($scope === 'user') {
|
if ($scope === 'user') {
|
||||||
$log_record = array(
|
// assign title to the field
|
||||||
// assign title to the field in the array record
|
$log_record = [
|
||||||
'time' => $item['time'],
|
'time' => $item['time'],
|
||||||
'log level' => $item['level'],
|
'log level' => $item['level'],
|
||||||
'log message' => $item['message']
|
'log message' => $item['message']
|
||||||
);
|
];
|
||||||
} else {
|
} else {
|
||||||
$log_record = array(
|
// assign title to the field
|
||||||
// assign title to the field in the array record
|
$log_record = [
|
||||||
'userID' => $item['user_id'],
|
'userID' => $item['user_id'],
|
||||||
'username' => $item['username'],
|
'username' => $item['username'],
|
||||||
'time' => $item['time'],
|
'time' => $item['time'],
|
||||||
'log level' => $item['level'],
|
'log level' => $item['level'],
|
||||||
'log message' => $item['message']
|
'log message' => $item['message']
|
||||||
);
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
// populate the result array
|
$logs['records'][] = $log_record;
|
||||||
array_push($logs['records'], $log_record);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$username = $userObject->getUserDetails($userId)[0]['username'];
|
$username = $userObject->getUserDetails($userId)[0]['username'];
|
||||||
|
$page = 'logs'; // For pagination template
|
||||||
|
|
||||||
// Get any new feedback messages
|
\App\Helpers\Theme::include('page-header');
|
||||||
include_once dirname(__FILE__, 4) . '/app/helpers/feedback.php';
|
\App\Helpers\Theme::include('page-menu');
|
||||||
|
if ($validSession) {
|
||||||
|
\App\Helpers\Theme::include('page-sidebar');
|
||||||
|
}
|
||||||
|
|
||||||
// Load plugin helpers
|
include APP_PATH . 'helpers/feedback.php';
|
||||||
require_once PLUGIN_LOGS_PATH . 'helpers/logs_view_helper.php';
|
require_once PLUGIN_LOGS_PATH . 'helpers/logs_view_helper.php';
|
||||||
|
|
||||||
// Display messages list
|
|
||||||
include PLUGIN_LOGS_PATH . 'views/logs.php';
|
include PLUGIN_LOGS_PATH . 'views/logs.php';
|
||||||
|
|
||||||
|
\App\Helpers\Theme::include('page-footer');
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{
|
{
|
||||||
"name": "Logger Plugin",
|
"name": "Logger Plugin",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"description": "Initializes logging system via LoggerFactory"
|
"description": "Initializes logging system via LoggerFactory"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,16 +44,55 @@ Enable/disable registration in `totalmeet.conf.php`:
|
||||||
|
|
||||||
## Implementation
|
## Implementation
|
||||||
|
|
||||||
Uses simple callable dispatcher pattern for single-action plugin:
|
Uses callable dispatcher pattern with procedural handler functions:
|
||||||
```php
|
```php
|
||||||
register_plugin_route_prefix('register', [
|
register_plugin_route_prefix('register', [
|
||||||
'dispatcher' => function($context) {
|
'dispatcher' => function($action, array $context = []) {
|
||||||
require_once PLUGIN_REGISTER_PATH . 'controllers/register.php';
|
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',
|
'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
|
## Dependencies
|
||||||
|
|
||||||
None - functions independently.
|
None - functions independently.
|
||||||
|
|
|
||||||
|
|
@ -12,11 +12,16 @@ if (!defined('PLUGIN_REGISTER_PATH')) {
|
||||||
}
|
}
|
||||||
|
|
||||||
require_once PLUGIN_REGISTER_PATH . 'helpers.php';
|
require_once PLUGIN_REGISTER_PATH . 'helpers.php';
|
||||||
require_once PLUGIN_REGISTER_PATH . 'controllers/register.php';
|
|
||||||
|
|
||||||
// Register route with dispatcher class
|
// Register route with simple callable dispatcher
|
||||||
register_plugin_route_prefix('register', [
|
register_plugin_route_prefix('register', [
|
||||||
'dispatcher' => \Plugins\Register\Controllers\RegisterController::class,
|
'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;
|
||||||
|
},
|
||||||
'access' => 'public',
|
'access' => 'public',
|
||||||
'defaults' => ['action' => 'register'],
|
'defaults' => ['action' => 'register'],
|
||||||
'plugin' => 'register',
|
'plugin' => 'register',
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,11 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User Registration API Controller
|
* Register Plugin Controller
|
||||||
*
|
*
|
||||||
* Provides RESTful endpoints for user registration.
|
* Procedural handler used by the callable dispatcher.
|
||||||
* 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/feedback.php';
|
||||||
require_once APP_PATH . 'classes/user.php';
|
require_once APP_PATH . 'classes/user.php';
|
||||||
require_once APP_PATH . 'classes/validator.php';
|
require_once APP_PATH . 'classes/validator.php';
|
||||||
|
|
@ -22,55 +14,36 @@ require_once APP_PATH . 'helpers/theme.php';
|
||||||
require_once APP_PATH . 'includes/rate_limit_middleware.php';
|
require_once APP_PATH . 'includes/rate_limit_middleware.php';
|
||||||
require_once PLUGIN_REGISTER_PATH . 'models/register.php';
|
require_once PLUGIN_REGISTER_PATH . 'models/register.php';
|
||||||
|
|
||||||
class RegisterController
|
function register_plugin_handle_register(string $action, array $context = []): bool {
|
||||||
{
|
|
||||||
private $db;
|
|
||||||
private array $config;
|
|
||||||
private string $appRoot;
|
|
||||||
private $logger;
|
|
||||||
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
$this->db = App::db();
|
|
||||||
$this->config = App::config();
|
|
||||||
$this->appRoot = App::get('app_root') ?? '/';
|
|
||||||
$this->logger = App::get('logObject');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function handle(string $action, array $context = []): bool
|
|
||||||
{
|
|
||||||
$validSession = (bool)($context['valid_session'] ?? false);
|
$validSession = (bool)($context['valid_session'] ?? false);
|
||||||
$app_root = $context['app_root'] ?? $this->appRoot;
|
$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');
|
||||||
|
|
||||||
if (!$this->db) {
|
if (!$db) {
|
||||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration service unavailable. Please try again later.');
|
\Feedback::flash('ERROR', 'DEFAULT', 'Registration service unavailable. Please try again later.');
|
||||||
$this->renderForm($validSession, $app_root, ['registrationEnabled' => false]);
|
register_plugin_render_form($validSession, $app_root, ['registrationEnabled' => false]);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$this->isRegistrationEnabled()) {
|
if (!(bool)($config['registration_enabled'] ?? false)) {
|
||||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration is currently disabled.');
|
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration is currently disabled.');
|
||||||
$this->renderForm($validSession, $app_root, ['registrationEnabled' => false]);
|
register_plugin_render_form($validSession, $app_root, ['registrationEnabled' => false]);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
$this->handleSubmission($validSession, $app_root);
|
register_plugin_handle_submission($validSession, $app_root, $db, $logger);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->renderForm($validSession, $app_root);
|
register_plugin_render_form($validSession, $app_root);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function isRegistrationEnabled(): bool
|
function register_plugin_handle_submission(bool $validSession, string $app_root, $db, $logger = null): void {
|
||||||
{
|
checkRateLimit($db, 'register');
|
||||||
return (bool)($this->config['registration_enabled'] ?? false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function handleSubmission(bool $validSession, string $app_root): void
|
|
||||||
{
|
|
||||||
checkRateLimit($this->db, 'register');
|
|
||||||
|
|
||||||
$security = \SecurityHelper::getInstance();
|
$security = \SecurityHelper::getInstance();
|
||||||
$formData = $security->sanitizeArray(
|
$formData = $security->sanitizeArray(
|
||||||
|
|
@ -80,7 +53,7 @@ class RegisterController
|
||||||
|
|
||||||
if (!$security->verifyCsrfToken($formData['csrf_token'] ?? '')) {
|
if (!$security->verifyCsrfToken($formData['csrf_token'] ?? '')) {
|
||||||
\Feedback::flash('ERROR', 'DEFAULT', 'Invalid security token. Please try again.');
|
\Feedback::flash('ERROR', 'DEFAULT', 'Invalid security token. Please try again.');
|
||||||
$this->renderForm($validSession, $app_root, [
|
register_plugin_render_form($validSession, $app_root, [
|
||||||
'values' => ['username' => $formData['username'] ?? ''],
|
'values' => ['username' => $formData['username'] ?? ''],
|
||||||
]);
|
]);
|
||||||
return;
|
return;
|
||||||
|
|
@ -110,7 +83,7 @@ class RegisterController
|
||||||
|
|
||||||
if (!$validator->validate($rules)) {
|
if (!$validator->validate($rules)) {
|
||||||
\Feedback::flash('ERROR', 'DEFAULT', $validator->getFirstError());
|
\Feedback::flash('ERROR', 'DEFAULT', $validator->getFirstError());
|
||||||
$this->renderForm($validSession, $app_root, [
|
register_plugin_render_form($validSession, $app_root, [
|
||||||
'values' => ['username' => $formData['username'] ?? ''],
|
'values' => ['username' => $formData['username'] ?? ''],
|
||||||
]);
|
]);
|
||||||
return;
|
return;
|
||||||
|
|
@ -119,70 +92,68 @@ class RegisterController
|
||||||
$username = trim($formData['username']);
|
$username = trim($formData['username']);
|
||||||
$password = $formData['password'];
|
$password = $formData['password'];
|
||||||
|
|
||||||
|
$pdo = $db instanceof \PDO ? $db : $db->getConnection();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$register = new \Register($this->db);
|
$register = new \Register($pdo);
|
||||||
$result = $register->register($username, $password);
|
$result = $register->register($username, $password);
|
||||||
|
|
||||||
if ($result === true) {
|
if ($result === true) {
|
||||||
$this->logSuccessfulRegistration($username);
|
register_plugin_log_success($username, $db, $logger);
|
||||||
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration successful. You can log in now.');
|
\Feedback::flash('NOTICE', 'DEFAULT', 'Registration successful. You can log in now.');
|
||||||
header('Location: ' . $app_root . '?page=login');
|
header('Location: ' . $app_root . '?page=login');
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $result);
|
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $result);
|
||||||
$this->renderForm($validSession, $app_root, [
|
register_plugin_render_form($validSession, $app_root, [
|
||||||
'values' => ['username' => $username],
|
'values' => ['username' => $username],
|
||||||
]);
|
]);
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $e->getMessage());
|
\Feedback::flash('ERROR', 'DEFAULT', 'Registration failed: ' . $e->getMessage());
|
||||||
$this->renderForm($validSession, $app_root, [
|
register_plugin_render_form($validSession, $app_root, [
|
||||||
'values' => ['username' => $username],
|
'values' => ['username' => $username],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function logSuccessfulRegistration(string $username): void
|
function register_plugin_log_success(string $username, $db, $logger = null): void {
|
||||||
{
|
if (!$logger) {
|
||||||
if (!$this->logger) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$userModel = new \User($this->db);
|
$userModel = new \User($db);
|
||||||
$userRecord = $userModel->getUserId($username);
|
$userRecord = $userModel->getUserId($username);
|
||||||
$userId = $userRecord[0]['id'] ?? null;
|
$userId = $userRecord[0]['id'] ?? null;
|
||||||
$userIP = $_SERVER['REMOTE_ADDR'] ?? '';
|
$userIP = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||||
|
|
||||||
$this->logger->log(
|
$logger->log(
|
||||||
'info',
|
'info',
|
||||||
sprintf('Registration: New user "%s" registered successfully. IP: %s', $username, $userIP),
|
sprintf('Registration: New user "%s" registered successfully. IP: %s', $username, $userIP),
|
||||||
['user_id' => $userId, 'scope' => 'user']
|
['user_id' => $userId, 'scope' => 'user']
|
||||||
);
|
);
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
app_log('warning', 'RegisterController logging failed: ' . $e->getMessage(), ['scope' => 'plugin']);
|
app_log('warning', 'Register plugin logging failed: ' . $e->getMessage(), ['scope' => 'plugin']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function renderForm(bool $validSession, string $app_root, array $data = []): void
|
function register_plugin_render_form(bool $validSession, string $app_root, array $data = []): void {
|
||||||
{
|
|
||||||
$formValues = $data['values'] ?? ['username' => ''];
|
$formValues = $data['values'] ?? ['username' => ''];
|
||||||
$registrationEnabled = $data['registrationEnabled'] ?? true;
|
$registrationEnabled = $data['registrationEnabled'] ?? true;
|
||||||
|
|
||||||
Theme::include('page-header');
|
\App\Helpers\Theme::include('page-header');
|
||||||
Theme::include('page-menu');
|
\App\Helpers\Theme::include('page-menu');
|
||||||
if ($validSession) {
|
if ($validSession) {
|
||||||
Theme::include('page-sidebar');
|
\App\Helpers\Theme::include('page-sidebar');
|
||||||
}
|
}
|
||||||
|
|
||||||
include APP_PATH . 'helpers/feedback.php';
|
include APP_PATH . 'helpers/feedback.php';
|
||||||
|
|
||||||
$app_root_value = $app_root; // align variable name for template include
|
|
||||||
$app_root = $app_root_value;
|
|
||||||
$values = $formValues;
|
$values = $formValues;
|
||||||
|
$app_root = $app_root;
|
||||||
|
|
||||||
include PLUGIN_REGISTER_PATH . 'views/form-register.php';
|
include PLUGIN_REGISTER_PATH . 'views/form-register.php';
|
||||||
|
|
||||||
Theme::include('page-footer');
|
\App\Helpers\Theme::include('page-footer');
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{
|
{
|
||||||
"name": "Registration Plugin",
|
"name": "Registration Plugin",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"description": "Provides registration functionality as a plugin."
|
"description": "Provides registration functionality as a plugin."
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue