v0.9.2
This commit is contained in:
commit
8f8513f802
278 files changed
+18400
No files matched your search
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Concerns;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permissions\Sources;
|
||||
|
||||
/**
|
||||
* Put this on the User model of the host app (needs the Users module).
|
||||
*
|
||||
* A super admin may do everything of the manager. Everyone else may do what any of their
|
||||
* groups allows, or (config `manager.permissions`) what the roles of the site say. `is_super_admin` is never fillable and no form sets it: only
|
||||
* `manager:create-user` makes one. Keep it out of `$fillable` in the host model.
|
||||
*/
|
||||
trait HasManagerAccess
|
||||
{
|
||||
/** @return BelongsToMany<Group, $this> */
|
||||
public function managerGroups(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id')->withPivot('is_primary');
|
||||
}
|
||||
|
||||
/**
|
||||
* The group this account is filed under: a label and a start screen, nothing more. What the account may do is
|
||||
* always the sum of all its groups, the primary one included.
|
||||
*/
|
||||
public function managerPrimaryGroup(): ?Group
|
||||
{
|
||||
// A group that was attached without a choice (by the site itself) makes the first one the primary one.
|
||||
return $this->managerGroups->first(fn (Group $group) => (bool) $group->pivot->is_primary) ?? $this->managerGroups->sortBy('id')->first();
|
||||
}
|
||||
|
||||
public function isManagerSuperAdmin(): bool
|
||||
{
|
||||
return (bool) $this->getAttribute('is_super_admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything this account may do in the manager.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function managerPermissions(): array
|
||||
{
|
||||
$registry = app(ModuleRegistry::class);
|
||||
|
||||
if ($this->isManagerSuperAdmin()) {
|
||||
return $registry->permissionValues();
|
||||
}
|
||||
|
||||
$fromGroups = Sources::usesGroups() ? $this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all() : [];
|
||||
|
||||
return $registry->complete([...$fromGroups, ...Sources::fromHost($this)]);
|
||||
}
|
||||
|
||||
public function hasManagerPermission(string $permission): bool
|
||||
{
|
||||
return in_array($permission, $this->managerPermissions(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this account may do everything $other may. Someone who manages accounts only
|
||||
* touches accounts that stay within their own rights; otherwise a new password for a
|
||||
* mightier account would be a way up.
|
||||
*/
|
||||
public function managerOutranks(self $other): bool
|
||||
{
|
||||
if ($this->isManagerSuperAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === [];
|
||||
}
|
||||
|
||||
/** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */
|
||||
public function managerMayGive(Group $group): bool
|
||||
{
|
||||
return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Support\Costs\Ledger;
|
||||
|
||||
/**
|
||||
* Prices the rows of the site's TOKENS.md that have no kept price yet and keeps the answer. Run after a deploy, so a release is priced once
|
||||
* and the owner's screen never has to wait for a price source.
|
||||
*/
|
||||
class CostsPriceCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:costs-price';
|
||||
|
||||
protected $description = 'Ask the price source once what the rows of TOKENS.md cost that have no kept price yet, and keep the answer';
|
||||
|
||||
public function handle(Ledger $ledger): int
|
||||
{
|
||||
$items = $ledger->items();
|
||||
$kept = count(array_filter($items, fn (array $item) => $item['priced_by'] === 'service'));
|
||||
$fixed = count(array_filter($items, fn (array $item) => $item['priced_by'] === 'config'));
|
||||
$open = count(array_filter($items, fn (array $item) => $item['tokens'] > 0 && $item['priced_by'] === null));
|
||||
|
||||
$this->info(count($items)." rows: {$kept} with a kept price, {$fixed} priced with the fixed rates, {$open} without a price.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Concerns\HasManagerAccess;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/**
|
||||
* Checks that the manager is wired into the app, and says what to do when it is not. Meant for people and for
|
||||
* AI agents: `--json` prints one machine-readable report, and the exit code is non-zero when a check fails.
|
||||
*
|
||||
* php artisan manager:doctor [--json]
|
||||
*
|
||||
* A check is `ok`, `warn` (works, but look at it) or `fail` (the manager will not work).
|
||||
*/
|
||||
class DoctorCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:doctor {--json : Print the report as JSON}';
|
||||
|
||||
protected $description = 'Check that the manager is set up correctly in this app';
|
||||
|
||||
/** @var list<array{check: string, status: string, message: string, fix: string|null}> */
|
||||
private array $checks = [];
|
||||
|
||||
public function handle(ModuleRegistry $modules): int
|
||||
{
|
||||
$this->checkUserModel($modules);
|
||||
$this->checkTables($modules);
|
||||
$this->checkStoredPermissions($modules);
|
||||
$this->checkRoutes();
|
||||
$this->checkNames();
|
||||
$this->checkModules($modules);
|
||||
|
||||
$failed = collect($this->checks)->contains('status', 'fail');
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode(['ok' => ! $failed, 'checks' => $this->checks], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
} else {
|
||||
foreach ($this->checks as $check) {
|
||||
$line = sprintf('[%s] %s: %s', strtoupper($check['status']), $check['check'], $check['message']);
|
||||
$check['status'] === 'fail' ? $this->error($line) : ($check['status'] === 'warn' ? $this->warn($line) : $this->info($line));
|
||||
|
||||
if ($check['fix'] !== null && $check['status'] !== 'ok') {
|
||||
$this->line(' fix: '.$check['fix']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
private function add(string $check, string $status, string $message, ?string $fix = null): void
|
||||
{
|
||||
$this->checks[] = ['check' => $check, 'status' => $status, 'message' => $message, 'fix' => $fix];
|
||||
}
|
||||
|
||||
private function checkUserModel(ModuleRegistry $modules): void
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
|
||||
if (! is_string($model) || ! class_exists($model)) {
|
||||
$this->add('user_model', 'fail', 'manager.user_model is not a class: '.var_export($model, true), 'Set MANAGER_USER_MODEL (or manager.user_model) to your User model, for example App\\Models\\User.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add('user_model', 'ok', "The user model is {$model}.");
|
||||
|
||||
$guard = config('auth.defaults.guard');
|
||||
$loggedIn = config('auth.providers.'.config("auth.guards.{$guard}.provider").'.model');
|
||||
|
||||
if (is_string($loggedIn) && $loggedIn !== $model && ! is_subclass_of($loggedIn, $model) && ! is_subclass_of($model, $loggedIn)) {
|
||||
$this->add('auth_model', 'fail', "People log in as {$loggedIn} (config/auth.php), but manager.user_model is {$model}: the manager would not know their rights.", 'Point manager.user_model (MANAGER_USER_MODEL) at the same model as the auth provider.');
|
||||
}
|
||||
|
||||
if (! in_array(HasManagerAccess::class, class_uses_recursive($model), true)) {
|
||||
$this->add('user_trait', 'fail', "{$model} does not use HasManagerAccess.", "Add `use \\IriksIT\\Manager\\Concerns\\HasManagerAccess;` inside the class {$model}.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add('user_trait', 'ok', 'The user model uses HasManagerAccess.');
|
||||
|
||||
if (in_array('is_super_admin', (new $model)->getFillable(), true)) {
|
||||
$this->add('super_admin_fillable', 'fail', 'is_super_admin is mass assignable: anyone who can fill the model could make themselves a super admin.', 'Remove is_super_admin from $fillable of the user model.');
|
||||
}
|
||||
|
||||
if ($modules->enabled('users') && Schema::hasTable((new $model)->getTable()) && Schema::hasTable(Names::table('groups'))) {
|
||||
$admins = $model::query()->where('is_super_admin', true)->count();
|
||||
$admins > 0
|
||||
? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.")
|
||||
: $this->add('super_admin', 'warn', 'There is no super admin yet: nobody can manage groups.', 'php artisan manager:create-user --name=... --email=... --password=...');
|
||||
}
|
||||
}
|
||||
|
||||
private function checkTables(ModuleRegistry $modules): void
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) {
|
||||
if (! Schema::hasTable(Names::table($table))) {
|
||||
$missing[] = Names::table($table);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$missing === []
|
||||
? $this->add('tables', 'ok', 'The tables of every active module exist.')
|
||||
: $this->add('tables', 'fail', 'Missing tables: '.implode(', ', $missing), 'php artisan migrate');
|
||||
|
||||
// A table of the site that the package adopted (`manager.tables`) may lack columns the package writes.
|
||||
$lacking = [];
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) {
|
||||
if ($missingColumns = Tables::missingColumns($table)) {
|
||||
$lacking[] = Names::table($table).' ('.implode(', ', $missingColumns).')';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($lacking !== []) {
|
||||
$this->add('columns', 'fail', 'Columns the manager needs are missing: '.implode('; ', $lacking), 'Add them with a migration of the site, or run `php artisan migrate` when the manager migrations have not run yet.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Rights stored in groups (by an earlier manager of the site, say) that no module of the package knows: they grant nothing. */
|
||||
private function checkStoredPermissions(ModuleRegistry $modules): void
|
||||
{
|
||||
$table = Names::table('groups');
|
||||
|
||||
if (! $modules->enabled('users') || ! Schema::hasTable($table) || ! Schema::hasColumn($table, 'permissions')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$known = $modules->permissionValues();
|
||||
$unknown = [];
|
||||
|
||||
foreach (DB::table($table)->pluck('permissions') as $stored) {
|
||||
foreach ((array) (is_string($stored) ? json_decode($stored, true) : $stored) as $permission) {
|
||||
if (is_string($permission) && ! in_array($permission, $known, true)) {
|
||||
$unknown[$permission] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$unknown === []
|
||||
? $this->add('stored_permissions', 'ok', 'Every right stored in a group is one the manager knows.')
|
||||
: $this->add('stored_permissions', 'warn', 'Groups hold rights that grant nothing: '.implode(', ', array_slice(array_keys($unknown), 0, 10)).'.', 'Name the list of the site after the right (a resource `navigation` gives `navigation.manage`), switch the module on, or remove the right from the group.');
|
||||
}
|
||||
|
||||
private function checkRoutes(): void
|
||||
{
|
||||
Route::has(Names::route('dashboard'))
|
||||
? $this->add('routes', 'ok', 'The manager routes are registered under /'.trim((string) config('manager.path'), '/').'.')
|
||||
: $this->add('routes', 'fail', 'The manager routes are not registered.', 'Run `composer dump-autoload` and make sure the package service provider is discovered (not in dont-discover).');
|
||||
|
||||
if (Route::has('login')) {
|
||||
$this->add('login', 'ok', 'The app has a login route.');
|
||||
} elseif (Route::has(Names::route('login'))) {
|
||||
$this->add('login', 'ok', 'The app has no login of its own: visitors use the login of the manager.');
|
||||
} else {
|
||||
$this->add('login', 'warn', 'There is no login: the auth middleware has nowhere to send visitors.', 'Set MANAGER_UI=package (the manager brings a login), or add a login to the app.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Route names or addresses of the site that the package would share with its own. */
|
||||
private function checkNames(): void
|
||||
{
|
||||
$prefix = Names::routePrefix();
|
||||
$path = trim((string) config('manager.path'), '/');
|
||||
$names = [];
|
||||
$foreign = [];
|
||||
|
||||
foreach (Route::getRoutes()->getRoutes() as $route) {
|
||||
$name = (string) $route->getName();
|
||||
$mine = $route->isFallback || ($route->getActionName() === 'Closure' && str_starts_with($name, $prefix)) || str_starts_with(ltrim($route->getActionName(), '\\'), 'IriksIT\\Manager\\');
|
||||
|
||||
if ($prefix !== '' && str_starts_with($name, $prefix) && $name !== $prefix) {
|
||||
$names[$name] = ($names[$name] ?? 0) + 1;
|
||||
}
|
||||
|
||||
if (! $mine && ($route->uri() === $path || str_starts_with($route->uri(), $path.'/'))) {
|
||||
$foreign[] = $route->uri();
|
||||
}
|
||||
}
|
||||
|
||||
$twice = array_keys(array_filter($names, fn (int $count) => $count > 1));
|
||||
|
||||
if ($twice !== []) {
|
||||
$this->add('names', 'warn', 'Route names used twice: '.implode(', ', array_slice($twice, 0, 5)).'. The site and the manager share them, and one of the two stops working.', "Set 'route_name' in config/manager.php to something the site does not use, for example 'cms'.");
|
||||
} elseif ($foreign !== []) {
|
||||
$this->add('names', 'warn', 'The site has routes under the address of the manager: '.implode(', ', array_slice($foreign, 0, 5)).'.', "Move them, or set 'path' in config/manager.php (MANAGER_PATH) to another address.");
|
||||
} else {
|
||||
$this->add('names', 'ok', 'No route name or address is shared with the site.');
|
||||
}
|
||||
}
|
||||
|
||||
private function checkModules(ModuleRegistry $modules): void
|
||||
{
|
||||
$active = array_keys($modules->active());
|
||||
$this->add('modules', 'ok', 'Active modules: '.implode(', ', $active).'.');
|
||||
|
||||
if ($modules->enabled('media')) {
|
||||
$disk = config('manager.media.disk');
|
||||
config("filesystems.disks.{$disk}") === null
|
||||
? $this->add('media_disk', 'fail', "The media disk \"{$disk}\" is not in config/filesystems.php.", 'Set MANAGER_MEDIA_DISK to a disk that exists.')
|
||||
: $this->add('media_disk', 'ok', "The media disk is \"{$disk}\".");
|
||||
|
||||
if ($disk === 'public' && ! file_exists(public_path('storage'))) {
|
||||
$this->add('storage_link', 'warn', 'public/storage does not exist: uploaded files cannot be served from the public disk.', 'php artisan storage:link');
|
||||
}
|
||||
}
|
||||
|
||||
if ($modules->enabled('audit')) {
|
||||
$this->add('proxies', 'warn', 'The audit log stores the visitor address. Behind a proxy or load balancer, trusted proxies must be configured, or every visitor looks like one address and one bad actor can lock the manager out.', 'Configure trusted proxies (bootstrap/app.php: $middleware->trustProxies(...)) and set MANAGER_NEVER_BAN to your own address.');
|
||||
}
|
||||
|
||||
if ($modules->enabled('statistics')) {
|
||||
$pages = (array) config('manager.statistics.pages');
|
||||
$pages === ['/'] && ! config('manager.statistics.posts_path')
|
||||
? $this->add('statistics_pages', 'warn', 'Only the home page counts in the statistics.', 'Set manager.statistics.pages (and posts_path), or register a resolver with CountedPages::register().')
|
||||
: $this->add('statistics_pages', 'ok', 'The statistics count '.count($pages).' page(s) and '.(config('manager.statistics.posts_path') ? 'the posts' : 'no posts').'.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use InvalidArgumentException;
|
||||
use IriksIT\Manager\Support\Importer;
|
||||
|
||||
/**
|
||||
* Copies a site's existing table into a table of the package. The source is only read.
|
||||
*
|
||||
* php artisan manager:import posts --table=articles --map=title=headline --map=body=content --dry-run
|
||||
*
|
||||
* Mappings can also be set once in config `manager.import.<target>` (`table`, `connection`, `map`).
|
||||
*/
|
||||
class ImportCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:import {target : posts, pages, reviews, media, leads or taps}
|
||||
{--table= : Table to read (default: config manager.import.<target>.table)}
|
||||
{--connection= : Database connection of that table (default: the default one)}
|
||||
{--map=* : package_column=source_column, repeat for each column that is named differently}
|
||||
{--set=* : package_column=value, a value for every row that has none (for media: --set=disk=iriksit)}
|
||||
{--limit= : Only the first rows}
|
||||
{--dry-run : Count what would happen and write nothing}';
|
||||
|
||||
protected $description = 'Copy the existing posts, pages, reviews, media, leads or taps rows of the site into the package tables';
|
||||
|
||||
public function handle(Importer $importer): int
|
||||
{
|
||||
$target = (string) $this->argument('target');
|
||||
$config = (array) config('manager.import.'.$target, []);
|
||||
$table = $this->option('table') ?: ($config['table'] ?? null);
|
||||
|
||||
if (! is_string($table) || $table === '') {
|
||||
$this->error('Which table? Give --table=... or set manager.import.'.$target.'.table.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$map = (array) ($config['map'] ?? []);
|
||||
|
||||
foreach ((array) $this->option('map') as $pair) {
|
||||
if (! str_contains((string) $pair, '=')) {
|
||||
$this->error("--map wants package_column=source_column, got {$pair}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
[$to, $from] = explode('=', (string) $pair, 2);
|
||||
$map[trim($to)] = trim($from);
|
||||
}
|
||||
|
||||
$fixed = [];
|
||||
|
||||
foreach ((array) $this->option('set') as $pair) {
|
||||
if (! str_contains((string) $pair, '=')) {
|
||||
$this->error("--set wants package_column=value, got {$pair}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
[$column, $value] = explode('=', (string) $pair, 2);
|
||||
$fixed[trim($column)] = $value;
|
||||
}
|
||||
|
||||
try {
|
||||
$connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null));
|
||||
$result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null, $fixed);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->error($e->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
foreach ($result['problems'] as $problem) {
|
||||
$this->warn($problem);
|
||||
}
|
||||
|
||||
$this->info(($this->option('dry-run') ? 'Dry run: ' : '')."{$result['created']} created, {$result['updated']} updated, {$result['skipped']} skipped.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* Sets the manager up in an app, without asking anything when the options are given.
|
||||
*
|
||||
* php artisan manager:install --modules=users,media,posts,audit --user-model="App\Models\User" --migrate
|
||||
*
|
||||
* It publishes the config, writes the MANAGER_* switches to .env, optionally runs the migrations, and finishes with
|
||||
* `manager:doctor`, which says what is still left to do (the trait on the user model, the first super admin).
|
||||
*/
|
||||
class InstallCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:install
|
||||
{--modules= : Comma-separated modules to switch ON (the rest of the optional ones are switched off)}
|
||||
{--user-model= : The Eloquent user model (default: what manager.user_model says)}
|
||||
{--path= : URL prefix of the manager (default: manager)}
|
||||
{--migrate : Run the migrations}
|
||||
{--json : Print the doctor report as JSON}';
|
||||
|
||||
protected $description = 'Set up the manager in this app: config, .env switches, migrations, then a health check';
|
||||
|
||||
public function handle(ModuleRegistry $modules): int
|
||||
{
|
||||
$this->callSilently('vendor:publish', ['--tag' => 'manager-config']);
|
||||
|
||||
$env = [];
|
||||
|
||||
if ($list = $this->option('modules')) {
|
||||
$wanted = array_filter(array_map('trim', explode(',', $list)));
|
||||
$unknown = array_diff($wanted, array_keys($modules->all()));
|
||||
|
||||
if ($unknown !== []) {
|
||||
$this->error('Unknown module(s): '.implode(', ', $unknown).'. Known: '.implode(', ', array_keys($modules->all())).'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
foreach (array_keys($modules->all()) as $key) {
|
||||
if (in_array($key, ['users', 'media'], true)) {
|
||||
continue; // switched in config, on by default
|
||||
}
|
||||
|
||||
$env['MANAGER_'.strtoupper($key)] = in_array($key, $wanted, true) ? 'true' : 'false';
|
||||
}
|
||||
}
|
||||
|
||||
if ($model = $this->option('user-model')) {
|
||||
$env['MANAGER_USER_MODEL'] = $model;
|
||||
}
|
||||
|
||||
if ($path = $this->option('path')) {
|
||||
$env['MANAGER_PATH'] = trim($path, '/');
|
||||
}
|
||||
|
||||
foreach ($env as $key => $value) {
|
||||
$this->writeEnv($key, $value);
|
||||
}
|
||||
|
||||
if ($env !== []) {
|
||||
$this->line('Wrote to .env: '.implode(', ', array_map(fn ($k, $v) => "{$k}={$v}", array_keys($env), $env)).'. Run `php artisan config:clear` if the config is cached.');
|
||||
}
|
||||
|
||||
if ($this->option('migrate')) {
|
||||
// The switches were just written: a fresh process sees them, this one still has the old config.
|
||||
$this->line('Run `php artisan migrate` (a new process) so the migrations of the modules you switched on are loaded.');
|
||||
}
|
||||
|
||||
if ($env !== []) {
|
||||
// This process still has the old config: its check would report the old state. A new process is right.
|
||||
$this->line('Next: add the HasManagerAccess trait to the user model, run `php artisan config:clear && php artisan migrate && php artisan storage:link`, then `php artisan manager:doctor --json`.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
return Artisan::call('manager:doctor', $this->option('json') ? ['--json' => true] : [], $this->output) === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
private function writeEnv(string $key, string $value): void
|
||||
{
|
||||
$file = base_path('.env');
|
||||
$contents = file_exists($file) ? file_get_contents($file) : '';
|
||||
$line = "{$key}={$value}";
|
||||
|
||||
$contents = preg_match("/^{$key}=.*$/m", $contents)
|
||||
? preg_replace("/^{$key}=.*$/m", $line, $contents)
|
||||
: rtrim($contents, "\n")."\n{$line}\n";
|
||||
|
||||
file_put_contents($file, $contents);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadBlock;
|
||||
|
||||
/**
|
||||
* Removes what a privacy statement promises to remove: a request that did not become a job after `keep_days` (a year), spam after
|
||||
* `keep_spam_days` (30), and blocks that ran out. A request with the outcome "won" is a customer file: it is never removed here.
|
||||
*/
|
||||
class LeadsPruneCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:leads-prune {--dry-run : Only count}';
|
||||
|
||||
protected $description = 'Remove old requests, old spam and expired blocks';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$old = Lead::query()->where(fn ($q) => $q->whereNull('outcome')->orWhere('outcome', '!=', Lead::WON))
|
||||
->where('folder', '!=', Lead::SPAM)->where('created_at', '<', now()->subDays(max(1, (int) config('manager.leads.keep_days', 365))));
|
||||
$spam = Lead::query()->where('folder', Lead::SPAM)->where('created_at', '<', now()->subDays(max(1, (int) config('manager.leads.keep_spam_days', 30))));
|
||||
$blocks = LeadBlock::query()->whereNotNull('expires_at')->where('expires_at', '<', now());
|
||||
|
||||
$counts = ['requests' => $old->count(), 'spam' => $spam->count(), 'blocks' => $blocks->count()];
|
||||
|
||||
if (! $this->option('dry-run')) {
|
||||
$old->delete();
|
||||
$spam->delete();
|
||||
$blocks->delete();
|
||||
}
|
||||
|
||||
$this->components->info(($this->option('dry-run') ? 'Would remove' : 'Removed')." {$counts['requests']} requests, {$counts['spam']} spam, {$counts['blocks']} blocks.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Support\Themes;
|
||||
|
||||
/**
|
||||
* Makes a theme for the site's own look (its house style) as a JSON file the manager picks up by itself.
|
||||
*
|
||||
* php artisan manager:make-theme acme --brand=#e4002b --font="Inter, sans-serif" --logo=/img/logo.svg --name="Acme"
|
||||
*
|
||||
* The brand colour is the one that matters; the rest starts from the dark or the light theme (`--light`) and can be
|
||||
* set with the colour options. Set `MANAGER_THEME=acme` to make it what everyone sees until they choose.
|
||||
*/
|
||||
class MakeThemeCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:make-theme {key : Short name, lowercase letters, numbers and dashes}
|
||||
{--label= : Name in the theme picker}
|
||||
{--name= : Name of the site in the menu and on the login screen}
|
||||
{--logo= : Path (/img/logo.svg) or https address of a logo}
|
||||
{--brand= : Main colour, #rrggbb}
|
||||
{--brand-alt= : Second accent colour}
|
||||
{--ink= : Page background}
|
||||
{--panel= : Menu and card background}
|
||||
{--text= : Text colour}
|
||||
{--light : Start from the light theme}
|
||||
{--font= : Font stack of the text}
|
||||
{--font-display= : Font stack of the headings}
|
||||
{--radius= : Corner radius, for example 0.5rem or 4px}
|
||||
{--path= : Folder for the file (default: resources/manager-themes)}
|
||||
{--force : Overwrite an existing theme}';
|
||||
|
||||
protected $description = 'Make a theme in the house style of the site';
|
||||
|
||||
public function handle(Themes $themes): int
|
||||
{
|
||||
$key = (string) $this->argument('key');
|
||||
|
||||
if (! preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', $key)) {
|
||||
$this->error('The key may only hold lowercase letters, numbers and dashes.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$raw = [
|
||||
'label' => $this->option('label') ?: ucfirst($key),
|
||||
'scheme' => $this->option('light') ? 'light' : 'dark',
|
||||
'name' => $this->option('name'),
|
||||
'logo' => $this->option('logo'),
|
||||
'font' => $this->option('font'),
|
||||
'font_display' => $this->option('font-display'),
|
||||
'radius' => $this->option('radius'),
|
||||
'colors' => array_filter([
|
||||
'brand' => $this->option('brand'), 'brand_alt' => $this->option('brand-alt'), 'ink' => $this->option('ink'),
|
||||
'panel' => $this->option('panel'), 'text' => $this->option('text'),
|
||||
]),
|
||||
];
|
||||
|
||||
// What the manager would accept: tell what was thrown away instead of silently writing a different theme.
|
||||
$clean = $themes->sanitize($key, $raw);
|
||||
$rejected = [];
|
||||
|
||||
foreach ($raw['colors'] as $name => $value) {
|
||||
($clean['colors'][$name] ?? null) === $value || $rejected[] = $name.' ('.$value.')';
|
||||
}
|
||||
|
||||
foreach (['radius', 'font', 'font_display', 'logo'] as $option) {
|
||||
$raw[$option] !== null && ($clean[$option] ?? null) !== $raw[$option] && $rejected[] = $option.' ('.$raw[$option].')';
|
||||
}
|
||||
|
||||
if ($rejected !== []) {
|
||||
$this->error('Not accepted: '.implode(', ', $rejected).'. Colours are #rgb or #rrggbb; no quotes or semicolons in fonts.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$folder = $this->option('path') ?: (config('manager.themes_path') ?: resource_path('manager-themes'));
|
||||
$file = rtrim($folder, '/')."/{$key}.json";
|
||||
|
||||
if (file_exists($file) && ! $this->option('force')) {
|
||||
$this->error("{$file} exists. Use --force to overwrite it.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
is_dir($folder) || mkdir($folder, 0775, true);
|
||||
$out = array_filter(['label' => $clean['label'], 'scheme' => $clean['scheme'], 'name' => $clean['name'], 'logo' => $clean['logo'], 'font' => $clean['font'], 'font_display' => $clean['font_display'], 'radius' => $clean['radius'], 'colors' => $clean['colors']], fn ($value) => $value !== null);
|
||||
file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
|
||||
|
||||
$this->info("Wrote {$file}. Everyone sees it with MANAGER_THEME={$key}; each account can pick it in its profile.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Modules\Media\MediaLibrary;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Moves the files of the media library to another disk, for instance from this server to the IriksIT API. The address of a file
|
||||
* does not change, so nothing that uses it needs editing. Safe to run again: what already lives on the disk is skipped, and a
|
||||
* file that fails stays where it was.
|
||||
*
|
||||
* php artisan manager:media-move iriksit --dry-run
|
||||
* php artisan manager:media-move iriksit --from=public --verify --delete-source
|
||||
*/
|
||||
class MediaMoveCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:media-move {to : The disk to move the files to}
|
||||
{--from= : Only move the files that are on this disk}
|
||||
{--limit=0 : Move at most this many files (0 = all)}
|
||||
{--verify : Read each copy back and compare it with the checksum}
|
||||
{--delete-source : Delete the original after the copy was checked}
|
||||
{--dry-run : Only show what would be moved}';
|
||||
|
||||
protected $description = 'Move the files of the media library to another disk';
|
||||
|
||||
public function handle(MediaLibrary $library): int
|
||||
{
|
||||
$to = (string) $this->argument('to');
|
||||
|
||||
if (config("filesystems.disks.{$to}") === null) {
|
||||
$this->error("There is no disk called {$to}.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$limit = max((int) $this->option('limit'), 0);
|
||||
$maxBytes = max(1, (int) config('manager.media.max_file_mb')) * 1024 * 1024;
|
||||
[$moved, $skipped, $failed] = [0, 0, 0];
|
||||
|
||||
$query = Media::query()->where('disk', '!=', $to)->when($this->option('from'), fn ($q, $from) => $q->where('disk', $from))->orderBy('id');
|
||||
|
||||
foreach ($query->get() as $media) {
|
||||
if ($limit > 0 && $moved + $failed >= $limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
$label = "#{$media->id} {$media->filename}";
|
||||
|
||||
if (! Storage::disk($media->disk)->exists($media->location)) {
|
||||
$this->warn("{$label}: not on the `{$media->disk}` disk, skipped.");
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $media->size > $maxBytes) {
|
||||
$this->warn("{$label}: larger than manager.media.max_file_mb, stays where it is.");
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($dryRun) {
|
||||
$this->line("{$label}: would be moved from `{$media->disk}`.");
|
||||
$moved++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$library->move($media, $to, (bool) $this->option('delete-source'), (bool) $this->option('verify'));
|
||||
} catch (MediaStorageException|Throwable $e) {
|
||||
$this->error("{$label}: could not be moved, left where it is ({$e->getMessage()})");
|
||||
$failed++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line("{$label}: moved.");
|
||||
$moved++;
|
||||
}
|
||||
|
||||
$this->info(($dryRun ? 'Would move' : 'Moved')." {$moved}, skipped {$skipped}, failed {$failed}.");
|
||||
|
||||
if (! $dryRun && $failed === 0 && config('manager.media.disk') !== $to) {
|
||||
$this->warn("manager.media.disk is not `{$to}` yet: new uploads still go to `".config('manager.media.disk').'`.');
|
||||
}
|
||||
|
||||
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Modules\Media\MediaLibrary;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Finds files of the media library that nothing uses any more (no post, page or other registered source holds their address),
|
||||
* and with `--delete` removes them. Nothing is deleted without `--delete`, and only files older than `--older-than` days.
|
||||
* `--orphans` looks for the opposite: files on a disk that no row knows (only for a disk that can list its files).
|
||||
*
|
||||
* php artisan manager:media-prune --older-than=30
|
||||
* php artisan manager:media-prune --older-than=30 --delete
|
||||
* php artisan manager:media-prune --orphans --disk=public
|
||||
*/
|
||||
class MediaPruneCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:media-prune
|
||||
{--older-than=30 : Only files that were added more than this many days ago}
|
||||
{--delete : Really delete (without this it only lists)}
|
||||
{--orphans : List (and with --delete, remove) files on the disk that no media row knows}
|
||||
{--disk= : For --orphans: the disk to look at (default: the disk of the media library)}';
|
||||
|
||||
protected $description = 'Find media files that nothing uses any more, and delete them on request';
|
||||
|
||||
public function handle(MediaLibrary $library): int
|
||||
{
|
||||
return $this->option('orphans') ? $this->orphans() : $this->unused($library);
|
||||
}
|
||||
|
||||
private function unused(MediaLibrary $library): int
|
||||
{
|
||||
$days = max(0, (int) $this->option('older-than'));
|
||||
$candidates = Media::query()->where('created_at', '<', now()->subDays($days))->orderBy('id')->get();
|
||||
$counts = $library->usageCounts($candidates);
|
||||
$found = $deleted = $failed = 0;
|
||||
|
||||
foreach ($candidates as $media) {
|
||||
if (($counts[$media->id] ?? 0) > 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found++;
|
||||
$label = "#{$media->id} {$media->filename} (".round($media->size / 1024).' KB)';
|
||||
|
||||
if (! $this->option('delete')) {
|
||||
$this->line("{$label}: not used.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$library->delete($media);
|
||||
$this->line("{$label}: deleted.");
|
||||
$deleted++;
|
||||
} catch (Throwable $e) {
|
||||
$this->error("{$label}: could not be deleted ({$e->getMessage()})");
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->info($this->option('delete') ? "Deleted {$deleted}, failed {$failed}." : "{$found} not used. Run again with --delete to remove them.");
|
||||
|
||||
return $failed === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
private function orphans(): int
|
||||
{
|
||||
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
|
||||
$known = Media::query()->where('disk', $name)->pluck('location')->flip();
|
||||
$disk = Storage::disk($name);
|
||||
|
||||
try {
|
||||
$files = $disk->allFiles('media');
|
||||
} catch (Throwable) {
|
||||
$files = [];
|
||||
}
|
||||
|
||||
if ($files === [] && Media::query()->where('disk', $name)->exists()) {
|
||||
$this->warn("The disk `{$name}` cannot list its files (or has none), so there is nothing to compare.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$found = 0;
|
||||
|
||||
foreach ($files as $file) {
|
||||
if ($known->has($file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found++;
|
||||
$this->line($this->option('delete') ? "{$file}: ".($disk->delete($file) ? 'deleted.' : 'could not be deleted.') : "{$file}: no row knows it.");
|
||||
}
|
||||
|
||||
$this->info($this->option('delete') ? "Looked at {$found} unknown files." : "{$found} files that no row knows. Run again with --delete to remove them.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Support\Settings\Definitions;
|
||||
use IriksIT\Manager\Support\Settings\Store;
|
||||
use IriksIT\Manager\Support\Settings\Writer;
|
||||
|
||||
/**
|
||||
* The settings screen in the terminal, for scripts, deploys and agents. Whoever may run this may change everything, so there is
|
||||
* no password or right to ask for. A secret is never printed, and its value is typed hidden (or read from standard input), never
|
||||
* given as an argument that would stay in the history of the shell.
|
||||
*
|
||||
* php artisan manager:settings list
|
||||
* php artisan manager:settings set manager.modules.reviews true
|
||||
* php artisan manager:settings set manager.media.iriksit.password (asks, hidden)
|
||||
* echo "$SECRET" | php artisan manager:settings set manager.login.turnstile.secret --stdin
|
||||
* php artisan manager:settings reset manager.modules.reviews
|
||||
* php artisan manager:settings refresh
|
||||
*/
|
||||
class SettingsCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:settings {action : list, get, set, reset or refresh}
|
||||
{key? : The config path of the setting, like manager.modules.reviews}
|
||||
{value? : The new value (not for a secret)}
|
||||
{--stdin : Read the value from standard input (for a secret in a script)}
|
||||
{--json : list: print JSON}';
|
||||
|
||||
protected $description = 'List, read, change or reset the settings of the settings screen';
|
||||
|
||||
public function handle(Definitions $definitions, Store $store, Writer $writer): int
|
||||
{
|
||||
$action = (string) $this->argument('action');
|
||||
|
||||
if ($action === 'refresh') {
|
||||
$this->info($writer->refresh() ? 'Refreshed.' : 'The caches are emptied, but the file bootstrap/cache/manager-settings.php could not be written.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($action === 'list') {
|
||||
return $this->list($definitions, $store);
|
||||
}
|
||||
|
||||
if (! in_array($action, ['get', 'set', 'reset'], true)) {
|
||||
$this->error('Use one of: list, get, set, reset, refresh.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$key = (string) $this->argument('key');
|
||||
$definition = $definitions->find($key);
|
||||
|
||||
if ($definition === null) {
|
||||
$this->error("There is no setting {$key}. See: php artisan manager:settings list");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($action === 'get') {
|
||||
$this->line($definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($action === 'reset') {
|
||||
$result = $writer->apply([$key => null]);
|
||||
$this->info("{$key} is back to what the config says.".($result['file_written'] ? '' : ' (The compiled file could not be written.)'));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
return $this->set($definitions, $writer, $definition);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $definition */
|
||||
private function set(Definitions $definitions, Writer $writer, array $definition): int
|
||||
{
|
||||
$key = $definition['key'];
|
||||
|
||||
if ($this->option('stdin')) {
|
||||
$raw = rtrim((string) stream_get_contents(STDIN), "\r\n");
|
||||
} elseif ($definition['type'] === 'secret') {
|
||||
if ($this->argument('value') !== null) {
|
||||
$this->error('Do not type a secret as an argument: it stays in the history of the shell. Leave it out to be asked, or use --stdin.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$raw = (string) $this->secret($definition['label']);
|
||||
} else {
|
||||
$raw = $this->argument('value');
|
||||
|
||||
if ($raw === null) {
|
||||
$this->error('Which value? php artisan manager:settings set '.$key.' <value>');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$value = $definitions->cast($definition, $raw);
|
||||
} catch (\InvalidArgumentException) {
|
||||
$this->error('This value is not valid for '.$key.' ('.$definition['type'].').');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$result = $writer->apply([$key => $value]);
|
||||
$this->info("{$key} is set.".($result['env_written'] ? ' Written into .env too.' : '').($result['file_written'] ? '' : ' (The compiled file could not be written: run `manager:settings refresh` when it can.)'));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function list(Definitions $definitions, Store $store): int
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
foreach ($definitions->all() as $key => $definition) {
|
||||
$rows[] = [
|
||||
'key' => $key,
|
||||
'type' => $definition['type'],
|
||||
'value' => $definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)),
|
||||
'saved' => $store->has($key),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->table(['Setting', 'Type', 'Value', 'Saved here'], array_map(fn ($row) => [$row['key'], $row['type'], $row['value'], $row['saved'] ? 'yes' : ''], $rows));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function show(mixed $value): string
|
||||
{
|
||||
return is_bool($value) ? ($value ? 'true' : 'false') : (string) ($value ?? '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Tries the disk of the media library the way a real upload would: writes a small file, reads it back, checks that it is
|
||||
* the same and deletes it again. Leaves nothing behind (when the delete fails, it says which file is left).
|
||||
*
|
||||
* php artisan manager:storage-check [--disk=iriksit]
|
||||
*/
|
||||
class StorageCheckCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:storage-check {--disk= : The disk to try; default: the disk of the media library}';
|
||||
|
||||
protected $description = 'Write, read and delete a test file on the disk of the media library';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
|
||||
$disk = Storage::disk($name);
|
||||
$location = 'manager-check/'.bin2hex(random_bytes(6)).'.txt';
|
||||
$content = 'manager storage check '.now()->toIso8601String();
|
||||
|
||||
$this->line("Disk: {$name}");
|
||||
|
||||
try {
|
||||
$step = 'write';
|
||||
if (! $disk->put($location, $content)) {
|
||||
$this->components->error('The file could not be written. See the log of the app for the reason.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Written.');
|
||||
|
||||
$step = 'read';
|
||||
$back = $disk->get($location);
|
||||
if ($back !== $content) {
|
||||
$this->components->error('What was read back is not what was written.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Read back: the same.');
|
||||
|
||||
$step = 'delete';
|
||||
if (! $disk->delete($location)) {
|
||||
$this->components->error("The test file could not be deleted: {$location}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->components->info('Deleted.');
|
||||
} catch (MediaStorageException|Throwable $e) {
|
||||
$this->components->error("Could not {$step}: ".$e->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->components->info('The storage works.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* The accounts of the manager, with their groups. `--json` for scripts and agents.
|
||||
*
|
||||
* php artisan manager:users [--json]
|
||||
*/
|
||||
class UserListCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:users {--json : Print JSON}';
|
||||
|
||||
protected $description = 'List the accounts of the manager with their groups';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
$rows = [];
|
||||
|
||||
foreach ($model::query()->with('managerGroups')->orderBy('id')->get() as $user) {
|
||||
$primary = $user->managerPrimaryGroup();
|
||||
|
||||
$rows[] = [
|
||||
'id' => $user->getKey(),
|
||||
'name' => (string) $user->name,
|
||||
'email' => (string) $user->email,
|
||||
'super_admin' => $user->isManagerSuperAdmin(),
|
||||
'primary_group' => $primary?->name,
|
||||
'groups' => $user->managerGroups->pluck('name')->sort()->values()->all(),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->table(['Id', 'Name', 'Email', 'Super admin', 'Primary group', 'Groups'], array_map(
|
||||
fn ($row) => [$row['id'], $row['name'], $row['email'], $row['super_admin'] ? 'yes' : '', $row['primary_group'] ?? '', implode(', ', $row['groups'])],
|
||||
$rows,
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Sets a new password for an account, for someone who cannot log in. Typed hidden by default; `--generate` makes a long random
|
||||
* one and shows it once. The password is never an argument (it would stay in the history of the shell).
|
||||
*
|
||||
* php artisan manager:user-password [email protected] [--generate]
|
||||
*/
|
||||
class UserPasswordCommand extends Command
|
||||
{
|
||||
protected $signature = 'manager:user-password {email : The email address of the account}
|
||||
{--generate : Make a random password and show it once}';
|
||||
|
||||
protected $description = 'Set a new password for an account of the manager';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
$user = $model::query()->where('email', strtolower((string) $this->argument('email')))->first();
|
||||
|
||||
if ($user === null) {
|
||||
$this->error('There is no account with that email address.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($this->option('generate')) {
|
||||
$password = Str::password(20, symbols: false);
|
||||
} else {
|
||||
$password = (string) $this->secret('New password (min 12 characters)');
|
||||
|
||||
if (mb_strlen($password) < 12) {
|
||||
$this->error('The password must be at least 12 characters.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($password !== (string) $this->secret('Once more')) {
|
||||
$this->error('The two passwords are not the same.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
$user->forceFill(['password' => Hash::make($password)])->save();
|
||||
$this->info("New password for {$user->email} is set.");
|
||||
$this->option('generate') && $this->line($password);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Contracts;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Something more a login asks for: a captcha, a code from an authenticator app, a field of the site's own. List the class in
|
||||
* `manager.login.checks`. A check fails a login by throwing `Illuminate\Validation\ValidationException`.
|
||||
*/
|
||||
interface LoginCheck
|
||||
{
|
||||
/**
|
||||
* What the login form shows besides the email and the password. Each entry has a `name` (the key in the request) and a `type`:
|
||||
* `text`, `password`, `number` or `turnstile` (with a `site_key`); and optionally a `label`, `autocomplete` and `required`.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function fields(): array;
|
||||
|
||||
/** Runs first, before the password is looked at: a captcha belongs here. */
|
||||
public function before(Request $request): void;
|
||||
|
||||
/**
|
||||
* Runs when the email and password are right, before anyone is logged in: a second factor belongs here. When it refuses, the
|
||||
* attempt counts as a failed login (the audit log and the bans see it).
|
||||
*/
|
||||
public function after(Request $request, Authenticatable $user): void;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Contracts;
|
||||
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* One switchable part of the manager. A module that is off contributes nothing:
|
||||
* no routes, no migrations, no menu items, no permissions.
|
||||
*/
|
||||
interface Module
|
||||
{
|
||||
/** Short unique key, also the key in config('manager.modules'). */
|
||||
public function key(): string;
|
||||
|
||||
/** Name in the menu. */
|
||||
public function label(): string;
|
||||
|
||||
/** Core modules (users, media) are on unless a site explicitly turns them off. */
|
||||
public function enabledByDefault(): bool;
|
||||
|
||||
/** @return list<string> keys of modules this one cannot work without */
|
||||
public function requires(): array;
|
||||
|
||||
/**
|
||||
* Permissions this module adds. Values are prefixed by the module key.
|
||||
*
|
||||
* @return list<Permission>
|
||||
*/
|
||||
public function permissions(): array;
|
||||
|
||||
/** @return list<array{label: string, route: string, permission: string}> */
|
||||
public function navigation(): array;
|
||||
|
||||
/** Absolute path of the routes file, or null. */
|
||||
public function routes(): ?string;
|
||||
|
||||
/** Absolute path of a routes file outside the manager (no prefix, no manager middleware), or null. */
|
||||
public function publicRoutes(): ?string;
|
||||
|
||||
/** Absolute path of the migrations folder, or null. */
|
||||
public function migrations(): ?string;
|
||||
|
||||
/** @return list<class-string> Artisan commands this module adds */
|
||||
public function commands(): array;
|
||||
|
||||
/**
|
||||
* What the audit log calls each thing that is done through this module's routes, by route
|
||||
* name without the `manager.` prefix: `[label]` or `[label, [form fields that may be kept]]`.
|
||||
* Never list a field a secret could be typed in.
|
||||
*
|
||||
* @return array<string, array{0: string, 1?: list<string>}>
|
||||
*/
|
||||
public function actions(): array;
|
||||
|
||||
/**
|
||||
* What the audit log calls opening a page (a GET route), by route name without `manager.`.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function views(): array;
|
||||
|
||||
/**
|
||||
* Middleware this module wants around every manager route: `before` runs ahead of the site's
|
||||
* own manager middleware (session, login), `after` behind it.
|
||||
*
|
||||
* @return array{before?: list<string>, after?: list<string>}
|
||||
*/
|
||||
public function middleware(): array;
|
||||
|
||||
/** Runs at boot, only when the module is on (register rate limiters, usage sources, ...). */
|
||||
public function boot(): void;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Contracts;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
|
||||
/**
|
||||
* Where a site that has roles of its own says what an account may do in the manager (config `manager.permissions.resolver`).
|
||||
* Values that are no permission of an active module are ignored, and what a permission needs is added.
|
||||
*/
|
||||
interface PermissionResolver
|
||||
{
|
||||
/** @return list<string> permission values such as `posts.write` */
|
||||
public function permissions(Authenticatable $user): array;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Contracts;
|
||||
|
||||
use IriksIT\Manager\Models\SocialConnection;
|
||||
use IriksIT\Manager\Support\Sharing\ShareContent;
|
||||
use IriksIT\Manager\Support\Sharing\SharedPost;
|
||||
use IriksIT\Manager\Support\Sharing\SharingException;
|
||||
|
||||
/**
|
||||
* Connecting with one platform (a social network) and posting on it. A site adds its own platform by implementing this and
|
||||
* listing the class in `manager.sharing.platforms`.
|
||||
*/
|
||||
interface Sharer
|
||||
{
|
||||
/** The name the owner reads, for example `LinkedIn`. */
|
||||
public function label(): string;
|
||||
|
||||
/**
|
||||
* The longest text the platform takes for the words of a post.
|
||||
*/
|
||||
public function maxLength(): int;
|
||||
|
||||
/** The app of the platform is set up (its id and secret are known). */
|
||||
public function canConnect(): bool;
|
||||
|
||||
/** What is missing to connect, for the owner: the labels of the settings to fill in. */
|
||||
public function missing(): string;
|
||||
|
||||
public function connection(): ?SocialConnection;
|
||||
|
||||
/** The name of the account the site posts as, for the manager. */
|
||||
public function accountName(): ?string;
|
||||
|
||||
/**
|
||||
* @param string $verifier a secret of this one attempt (PKCE); a platform that does not use it ignores it
|
||||
*/
|
||||
public function authorizationUrl(string $state, string $redirectUri, string $verifier): string;
|
||||
|
||||
/**
|
||||
* Trades the code the platform sent back for a token and stores the connection.
|
||||
*
|
||||
* @throws SharingException
|
||||
*/
|
||||
public function connect(string $code, string $redirectUri, string $verifier): SocialConnection;
|
||||
|
||||
public function disconnect(): void;
|
||||
|
||||
/**
|
||||
* Posts for real.
|
||||
*
|
||||
* @throws SharingException
|
||||
*/
|
||||
public function publish(ShareContent $content): SharedPost;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* The storage behind the media library could not store, return or delete a file.
|
||||
* `status` is 404 when the file is gone, 0 otherwise.
|
||||
*/
|
||||
class MediaStorageException extends RuntimeException
|
||||
{
|
||||
public function __construct(string $message, public readonly int $status = 0, public readonly ?int $retryAfter = null)
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Exceptions;
|
||||
|
||||
class ModuleException extends \LogicException {}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* @method static bool enabled(string $key)
|
||||
* @method static array active()
|
||||
* @method static array permissions()
|
||||
* @method static array permissionValues()
|
||||
* @method static array complete(array $values)
|
||||
* @method static array catalogue()
|
||||
* @method static array navigation()
|
||||
* @method static array actions()
|
||||
* @method static array views()
|
||||
*
|
||||
* @see ModuleRegistry
|
||||
*/
|
||||
class Manager extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor(): string
|
||||
{
|
||||
return ModuleRegistry::class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/** The built screens, served by the package itself: the app does not need Node, a build step or a publish. */
|
||||
class AssetController
|
||||
{
|
||||
private const FILES = ['manager.js' => 'application/javascript', 'manager.css' => 'text/css', 'vue.js' => 'application/javascript'];
|
||||
|
||||
public function __invoke(string $file): BinaryFileResponse
|
||||
{
|
||||
abort_unless(isset(self::FILES[$file]) && is_file($path = __DIR__.'/../../../resources/dist/'.$file), 404);
|
||||
|
||||
return response()->file($path, [
|
||||
'Content-Type' => self::FILES[$file],
|
||||
'Cache-Control' => 'public, max-age=31536000, immutable',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Tiles;
|
||||
|
||||
class DashboardController
|
||||
{
|
||||
public function __invoke(Request $request, ModuleRegistry $modules, Menu $menu, Tiles $tiles)
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// Only what this account may reach, in the face it looks at.
|
||||
$navigation = $menu->for($user, array_values(array_filter($modules->permissionValues(), fn (string $permission) => $user?->can($permission))));
|
||||
|
||||
// What the big buttons of the simple start screen say: by the address of the menu item.
|
||||
$facts = [];
|
||||
|
||||
foreach ($tiles->for($user) as $route => $fact) {
|
||||
$facts[route($route, [], false)] = $fact;
|
||||
}
|
||||
|
||||
$help = (array) config('manager.simple.help', []);
|
||||
$site = config('manager.simple.site_link', '/');
|
||||
|
||||
return $request->wantsJson()
|
||||
? response()->json([
|
||||
'navigation' => $navigation,
|
||||
'facts' => (object) $facts,
|
||||
// A way to ask for help (a name and a link, for example a WhatsApp link) and a link to the site, under the buttons.
|
||||
'help' => is_string($help['link'] ?? null) && ($help['link'] ?? '') !== '' ? ['name' => (string) ($help['name'] ?? ''), 'link' => $help['link']] : null,
|
||||
'site' => is_string($site) && $site !== '' ? $site : null,
|
||||
])
|
||||
: view('manager::dashboard', ['navigation' => $navigation]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Support\LoginChecks;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** The manager's own login, for an app that has none. Failed attempts reach the audit log through Laravel's `Failed` event. */
|
||||
class LoginController
|
||||
{
|
||||
public function store(Request $request, LoginChecks $checks): JsonResponse
|
||||
{
|
||||
$checks->before($request);
|
||||
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'password' => ['required', 'string', 'max:200'],
|
||||
]);
|
||||
|
||||
$refused = null;
|
||||
|
||||
// `attemptWhen` runs the second checks after the password is right and before the login begins; a refusal is a failed login.
|
||||
$loggedIn = Auth::attemptWhen($credentials, function ($user) use ($checks, $request, &$refused) {
|
||||
try {
|
||||
$checks->after($request, $user);
|
||||
} catch (ValidationException $e) {
|
||||
$refused = $e;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, $request->boolean('remember'));
|
||||
|
||||
if (! $loggedIn) {
|
||||
throw $refused ?? ValidationException::withMessages(['email' => trans('auth.failed')]);
|
||||
}
|
||||
|
||||
$request->session()->regenerate();
|
||||
|
||||
return response()->json(['redirect' => '/'.trim((string) config('manager.path'), '/')]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request): JsonResponse
|
||||
{
|
||||
Auth::guard()->logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return response()->json(['redirect' => Route::has(Names::route('login')) ? route(Names::route('login'), [], false) : '/']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Support\Markdown;
|
||||
|
||||
/** The preview of the editor: the text as the site renders it (raw HTML is escaped there, so the answer is safe to show). */
|
||||
class MarkdownController
|
||||
{
|
||||
public function __invoke(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['text' => ['nullable', 'string', 'max:200000']]);
|
||||
|
||||
return response()->json(['html' => Markdown::toHtml((string) ($data['text'] ?? ''))]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* The pictures of the tour. A picture is `<name>.webp` or `<name>.png` in `manager.mascot.path` (default: resources/mascot of
|
||||
* the package); a site can give its own set by pointing the path at a folder of its own. A picture that is not there is
|
||||
* answered with a small paw, so the tour works before the pictures do.
|
||||
*/
|
||||
class MascotController
|
||||
{
|
||||
/** What the tour asks for. */
|
||||
public const NAMES = ['welcome', 'point', 'calm', 'write', 'photos', 'pages', 'undo', 'oops', 'party', 'profile', 'peek'];
|
||||
|
||||
private const TYPES = ['webp' => 'image/webp', 'png' => 'image/png'];
|
||||
|
||||
public function __invoke(string $name): BinaryFileResponse|Response
|
||||
{
|
||||
abort_unless(in_array($name, self::NAMES, true), 404);
|
||||
|
||||
$folder = rtrim((string) (config('manager.mascot.path') ?: __DIR__.'/../../../resources/mascot'), '/');
|
||||
|
||||
foreach (self::TYPES as $extension => $type) {
|
||||
if (is_file($path = "$folder/$name.$extension")) {
|
||||
return response()->file($path, ['Content-Type' => $type, 'Cache-Control' => 'public, max-age=86400', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
|
||||
return response(self::paw(), 200, ['Content-Type' => 'image/svg+xml', 'Cache-Control' => 'public, max-age=300', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
/** A paw: the stand-in for every picture that is not there yet. */
|
||||
private static function paw(): string
|
||||
{
|
||||
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><g fill="#f43f7a">'
|
||||
.'<ellipse cx="64" cy="84" rx="26" ry="22"/><ellipse cx="26" cy="58" rx="11" ry="15" transform="rotate(-20 26 58)"/>'
|
||||
.'<ellipse cx="50" cy="38" rx="11" ry="15" transform="rotate(-8 50 38)"/><ellipse cx="78" cy="38" rx="11" ry="15" transform="rotate(8 78 38)"/>'
|
||||
.'<ellipse cx="102" cy="58" rx="11" ry="15" transform="rotate(20 102 58)"/></g></svg>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
use IriksIT\Manager\Support\Themes;
|
||||
|
||||
/** Your own name, password and look. Never the rights: those are the groups'. */
|
||||
class ProfileController
|
||||
{
|
||||
public function show(Request $request, Themes $themes): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return response()->json(['profile' => [
|
||||
'name' => (string) $user->name,
|
||||
'email' => (string) $user->email,
|
||||
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
|
||||
'groups' => method_exists($user, 'managerGroups') ? $user->managerGroups()->pluck('name')->values() : [],
|
||||
'theme' => $themes->keyFor($user),
|
||||
'locale' => UserSetting::value($user, 'locale') ?? app()->getLocale(),
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'themes' => config('manager.user_themes')
|
||||
? collect($themes->all())->map(fn (array $theme, string $key) => ['key' => $key, 'label' => __($theme['label']), 'colors' => $theme['colors']])->values()
|
||||
: [],
|
||||
]]);
|
||||
}
|
||||
|
||||
/** The face of the manager (`full` or `simple`) an account that may switch looks at. */
|
||||
public function view(Request $request, Menu $menu): JsonResponse
|
||||
{
|
||||
abort_unless($menu->maySwitch($request->user()), 403);
|
||||
|
||||
$data = $request->validate(['view' => ['required', Rule::in([Menu::FULL, Menu::SIMPLE])]]);
|
||||
UserSetting::put($request->user(), ['view' => $data['view']]);
|
||||
|
||||
return response()->json(['view' => $data['view']]);
|
||||
}
|
||||
|
||||
/** Where the account stands with the tour: finished, skipped, or (to look at it again) pending. Any account may, for itself. */
|
||||
public function tutorial(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['state' => ['required', Rule::in(UserSetting::TUTORIAL)]]);
|
||||
UserSetting::put($request->user(), ['tutorial' => $data['state']]);
|
||||
|
||||
return response()->json(['tutorial' => $data['state']]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Themes $themes): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
app(AuditTrail::class)->about($user);
|
||||
|
||||
$data = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'current_password' => ['nullable', 'string', 'max:200'],
|
||||
'password' => ['nullable', 'string', 'min:12', 'max:200', 'confirmed'],
|
||||
'theme' => ['nullable', 'string', Rule::in(array_keys($themes->all()))],
|
||||
'locale' => ['nullable', 'string', Rule::in(UserSetting::LOCALES)],
|
||||
]);
|
||||
|
||||
if (($data['password'] ?? '') !== '' && ! Hash::check((string) ($data['current_password'] ?? ''), $user->getAuthPassword())) {
|
||||
return response()->json(['message' => $wrong = __('The current password is not right.'), 'errors' => ['current_password' => [$wrong]]], 422);
|
||||
}
|
||||
|
||||
$user->name = $data['name'];
|
||||
($data['password'] ?? '') !== '' && $user->password = Hash::make($data['password']);
|
||||
$user->save();
|
||||
|
||||
if (config('manager.user_themes') && $request->has('theme')) {
|
||||
UserSetting::put($user, ['theme' => $data['theme'] ?: null]);
|
||||
}
|
||||
|
||||
if ($request->has('locale')) {
|
||||
UserSetting::put($user, ['locale' => $data['locale'] ?: null]);
|
||||
}
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** `auth`, but a visitor goes to the login of the host app when it has one and to the manager's own login when not. */
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
if ($request->expectsJson()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Route::has('login') ? route('login') : (Route::has(Names::route('login')) ? route(Names::route('login')) : null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Support\Features;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** A public route of a feature: `->middleware('manager.feature:services')`. When the feature is off the page is not there. */
|
||||
final class RequireFeature
|
||||
{
|
||||
public function handle(Request $request, Closure $next, string $feature): Response
|
||||
{
|
||||
abort_unless(Features::on($feature), 404);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Shell;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The screens are one page that asks the JSON routes for its data. A browser that opens a manager address gets that
|
||||
* page; the page itself, and anything else that asks for JSON, gets the data. Downloads (route names `*.export`), the
|
||||
* two steps of a connection with another service (`*.connect` sends the browser away, `*.callback` is where it comes back), the
|
||||
* built files and the pictures of the tour are left alone.
|
||||
*/
|
||||
class ServeShell
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (config('manager.ui') !== 'package' || ! $request->isMethodSafe() || $request->wantsJson() || $request->ajax()) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$name = (string) $request->route()?->getName();
|
||||
|
||||
if (in_array($name, [Names::route('assets'), Names::route('mascot')], true) || str_ends_with($name, '.export') || str_ends_with($name, '.connect') || str_ends_with($name, '.callback')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return response()->view('manager::shell', app(Shell::class)->data($request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The language an account chose applies to everything the manager says to it (menu, messages, the shell), inside the
|
||||
* manager's routes only: the site's own pages keep the language of the site. Nothing chosen: the language of the app.
|
||||
*/
|
||||
class SetLocale
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$chosen = UserSetting::value($request->user(), 'locale');
|
||||
|
||||
if (in_array($chosen, UserSetting::LOCALES, true)) {
|
||||
app()->setLocale($chosen);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Mail;
|
||||
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
|
||||
/** A short confirmation to the visitor with what was sent (`manager.leads.confirm`, off by default). View: `manager::mail.lead-confirmation`. */
|
||||
class LeadConfirmation extends Mailable
|
||||
{
|
||||
public function __construct(public Lead $lead) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(subject: (string) __('We received your message'));
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(view: 'manager::mail.lead-confirmation', with: ['lead' => $this->lead]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Mail;
|
||||
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Support\Leads\Phone;
|
||||
|
||||
/**
|
||||
* Tells the owner about a new request with the same three buttons as the manager: call, WhatsApp, mail. Sent by the site from its own
|
||||
* address; the visitor is the Reply-To, never the sender (that fails the checks of mail providers). The view `manager::mail.lead-received`
|
||||
* can be replaced by a site (resources/views/vendor/manager/mail/lead-received.blade.php).
|
||||
*/
|
||||
class LeadReceived extends Mailable
|
||||
{
|
||||
public function __construct(public Lead $lead) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: $this->lead->kindLabel().' — '.$this->lead->name.($this->lead->subject ? ': '.$this->lead->subject : ''),
|
||||
replyTo: $this->lead->email ? [new Address($this->lead->email, $this->lead->name)] : [],
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
$digits = $this->lead->phone ? Phone::international($this->lead->phone) : null;
|
||||
|
||||
return new Content(view: 'manager::mail.lead-received', with: [
|
||||
'lead' => $this->lead,
|
||||
'callLink' => $digits ? 'tel:+'.$digits : null,
|
||||
'whatsappLink' => $digits ? 'https://wa.me/'.$digits : null,
|
||||
'mailLink' => $this->lead->email ? 'mailto:'.$this->lead->email : null,
|
||||
'managerLink' => url(config('manager.path').'/leads').'?open='.$this->lead->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Filesystem\FilesystemAdapter;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use IriksIT\Manager\Support\IriksStorage;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use League\Flysystem\Filesystem;
|
||||
|
||||
class ManagerServiceProvider extends ServiceProvider
|
||||
{
|
||||
/** Only a super admin: the groups decide what everyone else may do. Not a permission of a group. */
|
||||
public const MANAGE_GROUPS = 'groups.manage';
|
||||
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
|
||||
|
||||
// What was set on the settings screen goes over the config before anything reads it.
|
||||
Support\Settings\Store::overlay();
|
||||
|
||||
$this->app->singleton(Support\MediaUsage::class);
|
||||
$this->app->singleton(Support\AuditTrail::class);
|
||||
$this->app->singleton(Modules\Posts\PostLabels::class);
|
||||
|
||||
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
|
||||
// A config that was published before resources existed does not list their module.
|
||||
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class, Modules\Settings\SettingsModule::class, Modules\Leads\LeadsModule::class])),
|
||||
$app['config']->get('manager.modules', []),
|
||||
));
|
||||
}
|
||||
|
||||
public function boot(ModuleRegistry $modules): void
|
||||
{
|
||||
$modules->validate();
|
||||
|
||||
$this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config');
|
||||
$this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang');
|
||||
$this->loadViewsFrom(__DIR__.'/../resources/views', 'manager');
|
||||
// The blocks of a page: the views to change (they go where Laravel looks for a view of this package first) and the plain stylesheet.
|
||||
$this->publishes([__DIR__.'/../resources/views/blocks' => resource_path('views/vendor/manager/blocks')], 'manager-blocks');
|
||||
$this->publishes([__DIR__.'/../resources/blocks/blocks.css' => public_path('vendor/manager/blocks.css')], 'manager-blocks-assets');
|
||||
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
|
||||
|
||||
foreach ([
|
||||
'manager.auth' => Http\Middleware\Authenticate::class,
|
||||
'manager.shell' => Http\Middleware\ServeShell::class,
|
||||
'manager.locale' => Http\Middleware\SetLocale::class,
|
||||
'manager.feature' => Http\Middleware\RequireFeature::class,
|
||||
] as $alias => $class) {
|
||||
$this->claimAlias($alias, $class);
|
||||
}
|
||||
// @feature('services') … @endfeature: what only shows when the feature is on.
|
||||
Blade::if('feature', fn (string $key) => Support\Features::on($key));
|
||||
RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
|
||||
|
||||
$this->registerIriksStorage();
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
if ($module->migrations() !== null) {
|
||||
$this->loadMigrationsFrom($module->migrations());
|
||||
}
|
||||
|
||||
if ($this->app->runningInConsole() && $module->commands() !== []) {
|
||||
$this->commands($module->commands());
|
||||
}
|
||||
|
||||
$module->boot();
|
||||
}
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class, Console\StorageCheckCommand::class, Console\MediaMoveCommand::class, Console\SettingsCommand::class, Console\UserListCommand::class, Console\UserPasswordCommand::class, Console\MediaPruneCommand::class]);
|
||||
}
|
||||
|
||||
$this->registerGates($modules);
|
||||
$this->registerRoutes($modules);
|
||||
}
|
||||
|
||||
/**
|
||||
* The disk `iriksit`: files at the IriksIT API. A site that wants it sets `manager.media.disk` to `iriksit` (or any disk
|
||||
* of its own with `driver` => `iriksit` in config/filesystems.php) and gives the address and the account
|
||||
* in `manager.media.iriksit`. The disk is added here when the site has not made one itself.
|
||||
*/
|
||||
private function registerIriksStorage(): void
|
||||
{
|
||||
Storage::extend('iriksit', function ($app, array $config) {
|
||||
$adapter = new IriksStorage\Adapter(new IriksStorage\Client($config));
|
||||
|
||||
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
|
||||
});
|
||||
|
||||
if (config('filesystems.disks.iriksit') === null) {
|
||||
config(['filesystems.disks.iriksit' => ['driver' => 'iriksit', ...(array) config('manager.media.iriksit', [])]]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One gate per permission, and no Gate::before: a package must never answer for abilities
|
||||
* of the host app. A super admin passes inside hasManagerPermission, for these gates only.
|
||||
*/
|
||||
private function registerGates(ModuleRegistry $modules): void
|
||||
{
|
||||
foreach ($modules->permissionValues() as $permission) {
|
||||
Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission));
|
||||
}
|
||||
|
||||
Gate::define(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin());
|
||||
}
|
||||
|
||||
/** What the routes of the package say for each of its middleware aliases: always the class, never the alias. */
|
||||
private array $aliases = [];
|
||||
|
||||
/**
|
||||
* Offer an alias for a middleware of the package, unless the app already has one of that name for something else
|
||||
* (a site that had its own manager before the package, whose alias may even be set after this provider has booted).
|
||||
* The routes of the package never go through the alias, only through the class, so the site's alias keeps meaning
|
||||
* the site's middleware.
|
||||
*/
|
||||
private function claimAlias(string $alias, string $class): void
|
||||
{
|
||||
$this->aliases[$alias] = $class;
|
||||
|
||||
$taken = $this->app['router']->getMiddleware()[$alias] ?? null;
|
||||
|
||||
if ($taken === null || $taken === $class) {
|
||||
$this->app['router']->aliasMiddleware($alias, $class);
|
||||
}
|
||||
}
|
||||
|
||||
private function registerRoutes(ModuleRegistry $modules): void
|
||||
{
|
||||
$screens = config('manager.ui') === 'package';
|
||||
|
||||
if ($screens) {
|
||||
// Outside `auth`, but behind the bans of the modules.
|
||||
Route::middleware(['web', ...$modules->middleware('before'), $this->aliases['manager.shell']])
|
||||
->prefix(config('manager.path'))
|
||||
->name(Names::routePrefix())
|
||||
->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php'));
|
||||
}
|
||||
|
||||
Route::middleware([...$modules->middleware('before'), ...array_map(fn ($name) => $this->aliases[$name] ?? $name, config('manager.middleware')), $this->aliases['manager.locale'], ...($screens ? [$this->aliases['manager.shell']] : []), ...$modules->middleware('after')])
|
||||
->prefix(config('manager.path'))
|
||||
->name(Names::routePrefix())
|
||||
->group(function () use ($modules) {
|
||||
$this->loadRoutesFrom(__DIR__.'/../routes/manager.php');
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
if ($module->routes() !== null) {
|
||||
$this->loadRoutesFrom($module->routes());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Files for visitors: outside the manager, no prefix and none of its middleware.
|
||||
foreach ($modules->active() as $module) {
|
||||
if ($module->publicRoutes() !== null) {
|
||||
$this->loadRoutesFrom($module->publicRoutes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* One line of the audit log: a login, a failed login, or something an account did in the manager.
|
||||
* Written by IriksIT\Manager\Modules\Audit\AuditTrail only.
|
||||
*
|
||||
* @property array<string, mixed>|null $details
|
||||
* @property Carbon $created_at
|
||||
*/
|
||||
class AuditLog extends Model
|
||||
{
|
||||
public const LOGIN = 'login';
|
||||
|
||||
public const LOGIN_FAILED = 'login_failed';
|
||||
|
||||
public const LOGOUT = 'logout';
|
||||
|
||||
/** Something that was done in the manager. */
|
||||
public const ACTION = 'action';
|
||||
|
||||
/** A page of the manager that was opened. */
|
||||
public const VIEWED = 'viewed';
|
||||
|
||||
/** Something the account was not allowed to do. */
|
||||
public const REFUSED = 'refused';
|
||||
|
||||
public const BAN = 'ban';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['details' => 'array', 'created_at' => 'datetime'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/**
|
||||
* The rules of the audit log (one row, id 1): when an address is banned by itself and how long
|
||||
* the log is kept. Set in the manager.
|
||||
*/
|
||||
class AuditSetting extends Model
|
||||
{
|
||||
/** @var array<string, mixed> */
|
||||
protected $attributes = [
|
||||
'auto_ban' => true,
|
||||
// This many failed logins from one address ...
|
||||
'max_failures' => 10,
|
||||
// ... within this many minutes ...
|
||||
'window_minutes' => 30,
|
||||
// ... keep it out this long. 0: until someone lifts the ban.
|
||||
'ban_minutes' => 1440,
|
||||
'keep_days' => 90,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'auto_ban' => 'boolean',
|
||||
'max_failures' => 'integer',
|
||||
'window_minutes' => 'integer',
|
||||
'ban_minutes' => 'integer',
|
||||
'keep_days' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** The longest the log may be kept (config `manager.audit.max_keep_days`): what a privacy policy promises. */
|
||||
public static function maxKeepDays(): int
|
||||
{
|
||||
return max(7, (int) config('manager.audit.max_keep_days', 90));
|
||||
}
|
||||
|
||||
/** The rules as they are now: the saved row, or the defaults while nothing was saved. */
|
||||
public static function current(): self
|
||||
{
|
||||
return static::query()->find(1) ?? new self;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{auto_ban: bool, max_failures: int, window_minutes: int, ban_minutes: int, keep_days: int}
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'auto_ban' => (bool) $this->auto_ban,
|
||||
'max_failures' => (int) $this->max_failures,
|
||||
'window_minutes' => (int) $this->window_minutes,
|
||||
'ban_minutes' => (int) $this->ban_minutes,
|
||||
// Also for a row that was saved when more was allowed.
|
||||
'keep_days' => min(self::maxKeepDays(), (int) $this->keep_days),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/**
|
||||
* The page layout of a list: the blocks of the page of one record (a service, a project), in which `{record.<field>}` stands for a
|
||||
* field of the record. One row per resource key. See `Support\Blocks::forRecord()`.
|
||||
*/
|
||||
class BlockTemplate extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['blocks' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* A set of permissions with a name ("Writers"). Accounts are put in groups; a group is the
|
||||
* only place where permissions are set.
|
||||
*
|
||||
* @property list<string>|null $permissions
|
||||
*/
|
||||
class Group extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['permissions' => 'array'];
|
||||
}
|
||||
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(config('manager.user_model'), Names::table('group_user'), 'group_id', 'user_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* What the group allows, without anything that is no permission (any more), for instance
|
||||
* of a module that was switched off.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function allowed(): array
|
||||
{
|
||||
return app(ModuleRegistry::class)->complete($this->permissions ?? []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use IriksIT\Manager\Modules\Audit\IpBans;
|
||||
|
||||
/**
|
||||
* An address that is kept out of the manager (or, `whole_site`, off the site), until `expires_at`
|
||||
* or (null) until someone lifts it. Written by IpBans only.
|
||||
*
|
||||
* @property Carbon $created_at
|
||||
*/
|
||||
class IpBan extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['automatic' => 'boolean', 'whole_site' => 'boolean', 'hits' => 'integer', 'last_hit_at' => 'datetime', 'expires_at' => 'datetime', 'created_at' => 'datetime'];
|
||||
}
|
||||
|
||||
/** The list of bans for the whole site is kept in the cache (IpBans::wholeSite): any change makes it stale. */
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saved(fn () => IpBans::forgetWholeSite());
|
||||
static::deleted(fn () => IpBans::forgetWholeSite());
|
||||
}
|
||||
|
||||
/**
|
||||
* Bans that still keep their address out.
|
||||
*
|
||||
* @param Builder<IpBan> $query
|
||||
*/
|
||||
public function scopeActive(Builder $query): void
|
||||
{
|
||||
$query->where(fn (Builder $q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()));
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->expires_at === null || $this->expires_at->isFuture();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/**
|
||||
* What someone wrote down about an address: who or what it is, or why it was banned, and the
|
||||
* group it belongs to (`group_name`: addresses with the same name are banned and let back in
|
||||
* together). One note per address, kept until it is removed: unlike the audit log and an ended
|
||||
* ban it is never deleted by the prune command, so a privacy policy has to say so.
|
||||
*/
|
||||
class IpNote extends Model
|
||||
{
|
||||
/** One spelling per address, so the note of an IPv6 address is found however it is written. */
|
||||
public static function spell(string $ip): string
|
||||
{
|
||||
$packed = @inet_pton(trim($ip));
|
||||
$spelled = $packed === false ? false : inet_ntop($packed);
|
||||
|
||||
return $spelled === false ? trim($ip) : $spelled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/**
|
||||
* A request of a visitor. The folder is decided by `Support\Leads\Screening`: the inbox (a real request), "other" (acquisition and
|
||||
* what the visitor called something else) or spam.
|
||||
*/
|
||||
class Lead extends Model
|
||||
{
|
||||
public const INBOX = 'inbox';
|
||||
|
||||
public const OTHER = 'other';
|
||||
|
||||
public const SPAM = 'spam';
|
||||
|
||||
public const FOLDERS = [self::INBOX, self::OTHER, self::SPAM];
|
||||
|
||||
public const WON = 'won';
|
||||
|
||||
public const LOST = 'lost';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'reasons' => 'array', 'answers' => 'array', 'notes' => 'array', 'notify_failed' => 'boolean',
|
||||
'subject_id' => 'integer', 'opened_at' => 'datetime', 'handled_at' => 'datetime', 'notified_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** The real requests that still wait for the owner. */
|
||||
public function scopeWaiting(Builder $query): void
|
||||
{
|
||||
$query->where('folder', self::INBOX)->whereNull('handled_at');
|
||||
}
|
||||
|
||||
/** The real requests that were handled. */
|
||||
public function scopeHandled(Builder $query): void
|
||||
{
|
||||
$query->where('folder', self::INBOX)->whereNotNull('handled_at');
|
||||
}
|
||||
|
||||
/** What the owner reads for the kind: a name from `manager.leads.kinds`, else the kind itself. */
|
||||
public function kindLabel(): string
|
||||
{
|
||||
return (string) __((string) (config('manager.leads.kinds')[$this->kind] ?? ucfirst($this->kind)));
|
||||
}
|
||||
|
||||
/** What it is about, in a few words: the subject the site gave, or the kind of request. */
|
||||
public function aboutLine(): string
|
||||
{
|
||||
return $this->subject !== null && $this->subject !== '' ? $this->subject : $this->kindLabel();
|
||||
}
|
||||
|
||||
/** The text as it is compared with earlier ones: lowercase, without the spaces and marks around the words. */
|
||||
public static function hashOf(?string $message): ?string
|
||||
{
|
||||
$text = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower((string) $message)) ?? '');
|
||||
|
||||
// A few words ("call me") are the same for many honest people.
|
||||
return mb_strlen($text) < 40 ? null : hash('sha256', $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/** A sender that is kept out: a request from them is not refused, it lands in the spam folder with this as the reason. */
|
||||
class LeadBlock extends Model
|
||||
{
|
||||
public const EMAIL = 'email';
|
||||
|
||||
public const DOMAIN = 'domain';
|
||||
|
||||
public const PHONE = 'phone';
|
||||
|
||||
public const IP = 'ip';
|
||||
|
||||
public const TYPES = [self::EMAIL, self::DOMAIN, self::PHONE, self::IP];
|
||||
|
||||
/** Mail domains that are too large to block as a whole. */
|
||||
public const SHARED_DOMAINS = [
|
||||
'gmail.com', 'googlemail.com', 'hotmail.com', 'hotmail.nl', 'outlook.com', 'outlook.nl', 'live.nl', 'live.com', 'msn.com',
|
||||
'yahoo.com', 'icloud.com', 'me.com', 'ziggo.nl', 'kpnmail.nl', 'kpnplanet.nl', 'planet.nl', 'hetnet.nl', 'home.nl',
|
||||
'xs4all.nl', 'upcmail.nl', 'casema.nl', 'telfort.nl', 'tele2.nl', 'online.nl', 'quicknet.nl', 'proton.me', 'protonmail.com',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['expires_at' => 'datetime'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/** How often the phone number or the WhatsApp button was pressed on a page, per day: a counter and nothing else, no visitor, no address. */
|
||||
class LeadTap extends Model
|
||||
{
|
||||
public const CALL = 'call';
|
||||
|
||||
public const WHATSAPP = 'whatsapp';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['taps' => 'integer'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* One file in the media library. The row is the bookkeeping; the file itself is stored on the
|
||||
* filesystem disk `disk` under `location`.
|
||||
*/
|
||||
class Media extends Model
|
||||
{
|
||||
protected $hidden = ['disk', 'location'];
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return Names::table('media');
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['size' => 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float'];
|
||||
}
|
||||
|
||||
public function uploader(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(config('manager.user_model'), 'uploaded_by');
|
||||
}
|
||||
|
||||
public function isImage(): bool
|
||||
{
|
||||
return str_starts_with($this->mime_type, 'image/');
|
||||
}
|
||||
|
||||
/**
|
||||
* The start of this file's address. It holds the id, so it stays the same when the file is
|
||||
* renamed, and is what content is searched for to see where a file is used.
|
||||
*/
|
||||
public function urlPrefix(): string
|
||||
{
|
||||
return '/media-files/'.$this->id.'/';
|
||||
}
|
||||
|
||||
/**
|
||||
* The address visitors load the file from. It ends in /view on purpose: web servers tend to
|
||||
* answer anything that ends in .jpg themselves, as a file on disk, and never ask the app.
|
||||
*/
|
||||
public function url(): string
|
||||
{
|
||||
return $this->urlPrefix().rawurlencode($this->filename).'/view';
|
||||
}
|
||||
|
||||
/**
|
||||
* The focus point of the image behind an address from the library, as a CSS `object-position`
|
||||
* value ("30% 65%"). Null for any other address, or when no focus point was set.
|
||||
*/
|
||||
public static function focusFor(?string $url): ?string
|
||||
{
|
||||
if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']);
|
||||
|
||||
return $media instanceof self
|
||||
? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%'
|
||||
: null;
|
||||
}
|
||||
|
||||
/** What the manager shows. Never includes where the file is stored. */
|
||||
public function toLibraryItem(int $usageCount = 0): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'filename' => $this->filename,
|
||||
'url' => $this->url(),
|
||||
'mime_type' => $this->mime_type,
|
||||
'is_image' => $this->isImage(),
|
||||
'size' => $this->size,
|
||||
'width' => $this->width,
|
||||
'height' => $this->height,
|
||||
'alt' => $this->alt,
|
||||
'focus_x' => $this->focus_x,
|
||||
'focus_y' => $this->focus_y,
|
||||
'uploaded_by' => $this->uploader?->name,
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
'usage_count' => $usageCount,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** Base of the package models: tables get the configured prefix, e.g. manager_pages. */
|
||||
abstract class Model extends Eloquent
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return $this->table ?? Names::table(parent::getTable());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use IriksIT\Manager\Support\Blocks;
|
||||
use IriksIT\Manager\Support\Fields;
|
||||
|
||||
/**
|
||||
* A page of the site. A page with a definition (config `manager.pages.definitions`) keeps its texts in
|
||||
* `content`, one value per defined field; any other page keeps one text in `body`.
|
||||
*
|
||||
* The public site reads it with `Page::contentFor('home')`: the stored values over the defaults, so a page
|
||||
* that was never saved still has all its keys.
|
||||
*/
|
||||
class Page extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['content' => 'array', 'blocks' => 'array', 'is_published' => 'boolean'];
|
||||
}
|
||||
|
||||
/**
|
||||
* The definitions of the pages: slug => ['title' => ..., 'fields' => normalized fields].
|
||||
*
|
||||
* @return array<string, array{title: string, simple_title: ?string, fields: array<string, array<string, mixed>>, blocks: bool|list<string>}>
|
||||
*/
|
||||
public static function definitions(): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ((array) config('manager.pages.definitions', []) as $slug => $definition) {
|
||||
if (is_string($slug) && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) && is_array($definition)) {
|
||||
$out[$slug] = ['title' => (string) ($definition['title'] ?? ucfirst(str_replace('-', ' ', $slug))), 'simple_title' => Fields::simpleText($definition, 'title'), 'fields' => Fields::normalize((array) ($definition['fields'] ?? [])), 'blocks' => $definition['blocks'] ?? false];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the public site shows on a page: every defined key, stored or default.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function contentFor(string $slug): array
|
||||
{
|
||||
$fields = self::definitions()[$slug]['fields'] ?? [];
|
||||
$page = self::query()->where('slug', $slug)->first();
|
||||
|
||||
return Fields::values($fields, is_array($page?->content) ? $page->content : []);
|
||||
}
|
||||
|
||||
/**
|
||||
* The block types a page may hold: a page with a definition says so in `blocks` (`true` for every type, or a list of types);
|
||||
* a free page follows `manager.blocks.free_pages`. Empty: the page has no blocks.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function blockTypesFor(string $slug): array
|
||||
{
|
||||
$definition = self::definitions()[$slug] ?? null;
|
||||
$allowed = $definition !== null ? $definition['blocks'] : config('manager.blocks.free_pages', false);
|
||||
$known = array_keys(Blocks::types());
|
||||
|
||||
if ($allowed === true) {
|
||||
return $known;
|
||||
}
|
||||
|
||||
return is_array($allowed) ? array_values(array_intersect($known, array_map('strval', $allowed))) : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* One page someone looked at, within a visit.
|
||||
*
|
||||
* @property string $day
|
||||
*/
|
||||
class PageView extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['viewed_at' => 'datetime', 'hour' => 'integer', 'seconds' => 'integer'];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Visit, $this> */
|
||||
public function visit(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Visit::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Support\Markdown;
|
||||
|
||||
class Post extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'tags' => 'array',
|
||||
'is_featured' => 'boolean',
|
||||
'published_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts that are visible on the public site: published and not scheduled for later.
|
||||
*
|
||||
* @param Builder<Post> $query
|
||||
*/
|
||||
public function scopePublished(Builder $query): void
|
||||
{
|
||||
$query->whereNotNull('published_at')->where('published_at', '<=', now());
|
||||
}
|
||||
|
||||
public function isPublished(): bool
|
||||
{
|
||||
return $this->published_at !== null && $this->published_at->lte(now());
|
||||
}
|
||||
|
||||
/** `draft`, `scheduled` or `published`. */
|
||||
public function status(): string
|
||||
{
|
||||
return match (true) {
|
||||
$this->published_at === null => 'draft',
|
||||
$this->published_at->isFuture() => 'scheduled',
|
||||
default => 'published',
|
||||
};
|
||||
}
|
||||
|
||||
/** A slug for $title that no other post uses yet. */
|
||||
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
|
||||
{
|
||||
$base = Str::slug($title) ?: 'post';
|
||||
$slug = $base;
|
||||
$suffix = 2;
|
||||
|
||||
while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) {
|
||||
$slug = $base.'-'.$suffix++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
public function readingMinutes(): int
|
||||
{
|
||||
return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220));
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields a post card or listing needs, for the host's public pages.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toCard(): array
|
||||
{
|
||||
return [
|
||||
'title' => $this->title,
|
||||
'slug' => $this->slug,
|
||||
'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160),
|
||||
'cover_image' => $this->cover_image,
|
||||
'cover_focus' => Media::focusFor($this->cover_image),
|
||||
'category' => $this->category,
|
||||
'tags' => $this->tags ?? [],
|
||||
'is_featured' => $this->is_featured,
|
||||
'published_at' => $this->published_at?->toIso8601String(),
|
||||
'reading_minutes' => $this->readingMinutes(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/** A post shared on a platform, or about to be, and what came of it. */
|
||||
class PostShare extends Model
|
||||
{
|
||||
public const PENDING = 'pending';
|
||||
|
||||
public const SHARING = 'sharing';
|
||||
|
||||
public const SHARED = 'shared';
|
||||
|
||||
public const FAILED = 'failed';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['dry_run' => 'boolean', 'shared_at' => 'datetime'];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Post, $this> */
|
||||
public function post(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Post::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/** A record of a resource that has no model of the site: its values are in `data`. */
|
||||
class Record extends Model
|
||||
{
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['data' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
class Review extends Model {}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/** An earlier state of a post, a page or another record that keeps a history (module `revisions`). */
|
||||
class Revision extends Model
|
||||
{
|
||||
/** Only `created_at`, set when the state is kept. */
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['data' => 'array', 'changed' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/**
|
||||
* The account of a platform the site posts as. The name of the platform is the key: one connection per platform.
|
||||
* The tokens are stored encrypted and never go to a screen.
|
||||
*/
|
||||
class SocialConnection extends Model
|
||||
{
|
||||
protected $primaryKey = 'name';
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $hidden = ['access_token', 'refresh_token'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'access_token' => 'encrypted',
|
||||
'refresh_token' => 'encrypted',
|
||||
'expires_at' => 'datetime',
|
||||
'refresh_token_expires_at' => 'datetime',
|
||||
'details' => 'array',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** What one account chose for itself in the manager: its theme, which face of the manager it looks at, its language and where it stands with the tour. */
|
||||
class UserSetting extends Model
|
||||
{
|
||||
protected $fillable = ['user_id', 'theme', 'view', 'locale', 'tutorial'];
|
||||
|
||||
/** The languages the screens come in. */
|
||||
public const LOCALES = ['en', 'nl'];
|
||||
|
||||
/** Where an account stands with the tour: `pending` shows it at the next load; `done` and `skipped` never again until it is set to pending. */
|
||||
public const TUTORIAL = ['pending', 'done', 'skipped'];
|
||||
|
||||
/** What this account chose (a row is made when it has none yet). */
|
||||
public static function put(object $user, array $values): void
|
||||
{
|
||||
static::query()->updateOrCreate(['user_id' => $user->getKey()], $values);
|
||||
}
|
||||
|
||||
/** One value of what this account chose, or null. */
|
||||
public static function value(?object $user, string $column): ?string
|
||||
{
|
||||
return $user === null || $user->getKey() === null ? null : static::query()->where('user_id', $user->getKey())->value($column);
|
||||
}
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return Names::table('user_settings');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* One visit to the public site. `day` is kept as a plain 'Y-m-d' string on
|
||||
* purpose: see the migration.
|
||||
*
|
||||
* @property string $day
|
||||
*/
|
||||
class Visit extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'started_at' => 'datetime',
|
||||
'last_seen_at' => 'datetime',
|
||||
'hour' => 'integer',
|
||||
'weekday' => 'integer',
|
||||
'page_views' => 'integer',
|
||||
'seconds' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return HasMany<PageView, $this> */
|
||||
public function pageViews(): HasMany
|
||||
{
|
||||
return $this->hasMany(PageView::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* The random key that goes into today's visitor codes. A new one every day, and
|
||||
* the old ones are deleted: without its key a code can no longer be linked to an
|
||||
* IP address, not even by this site.
|
||||
*
|
||||
* @property string $day
|
||||
* @property string $salt
|
||||
*/
|
||||
class VisitorSalt extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $primaryKey = 'day';
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
public static function forToday(): string
|
||||
{
|
||||
$today = now()->toDateString();
|
||||
$salt = static::query()->where('day', $today)->value('salt');
|
||||
|
||||
if (is_string($salt)) {
|
||||
return $salt;
|
||||
}
|
||||
|
||||
static::forgetOld();
|
||||
|
||||
try {
|
||||
return static::query()->create(['day' => $today, 'salt' => Str::random(64)])->salt;
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
// Another visitor arrived in the same instant and made today's key.
|
||||
return static::query()->where('day', $today)->sole()->salt;
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes every key that is not today's. Returns how many. */
|
||||
public static function forgetOld(): int
|
||||
{
|
||||
$deleted = static::query()->where('day', '<', now()->toDateString())->delete();
|
||||
|
||||
return is_int($deleted) ? $deleted : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* What the tokens of one piece of work cost, as a price source worked it out once (`Support\Costs\Ledger`). Kept, because the
|
||||
* price of a day in the past does not change.
|
||||
*
|
||||
* @property int $id
|
||||
* @property string $fingerprint
|
||||
* @property string $date
|
||||
* @property string $name
|
||||
* @property string|null $version
|
||||
* @property string $model
|
||||
* @property string $usd
|
||||
* @property string $eur
|
||||
* @property string $usd_per_eur
|
||||
*/
|
||||
class WorkCost extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['priced_at' => 'datetime'];
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
return Names::table('work_costs');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Models\AuditSetting;
|
||||
use IriksIT\Manager\Models\IpBan;
|
||||
use IriksIT\Manager\Models\IpNote;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\UserAgent;
|
||||
|
||||
/**
|
||||
* The audit log: the log itself, the addresses that are banned and the rules. Seeing it takes
|
||||
* "audit.view"; banning, lifting and the rules "audit.manage".
|
||||
*/
|
||||
class AuditController
|
||||
{
|
||||
private const PER_PAGE = 50;
|
||||
|
||||
/** What the log can be narrowed down to. */
|
||||
private const SHOW = ['all', 'logins', 'failed', 'actions', 'viewed', 'refused', 'bans'];
|
||||
|
||||
public function __construct(private readonly IpBans $bans, private readonly AuditTrail $trail) {}
|
||||
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$show = $request->string('show')->toString();
|
||||
|
||||
$filters = [
|
||||
'show' => in_array($show, self::SHOW, true) ? $show : 'all',
|
||||
'user' => $request->integer('user') ?: null,
|
||||
'ip' => $request->string('ip')->trim()->toString(),
|
||||
'q' => $request->string('q')->trim()->toString(),
|
||||
];
|
||||
|
||||
$query = AuditLog::query();
|
||||
|
||||
match ($filters['show']) {
|
||||
'logins' => $query->whereIn('event', [AuditLog::LOGIN, AuditLog::LOGOUT]),
|
||||
'failed' => $query->where('event', AuditLog::LOGIN_FAILED),
|
||||
'actions' => $query->where('event', AuditLog::ACTION),
|
||||
'viewed' => $query->where('event', AuditLog::VIEWED),
|
||||
'refused' => $query->where('event', AuditLog::REFUSED),
|
||||
'bans' => $query->where(fn (Builder $q) => $q->where('event', AuditLog::BAN)->orWhere('subject_type', 'ip_ban')),
|
||||
default => $query,
|
||||
};
|
||||
|
||||
if ($filters['user'] !== null) {
|
||||
$query->where('user_id', $filters['user']);
|
||||
}
|
||||
|
||||
if ($filters['ip'] !== '') {
|
||||
$query->where('ip', $filters['ip']);
|
||||
}
|
||||
|
||||
if ($filters['q'] !== '') {
|
||||
$like = '%'.addcslashes($filters['q'], '%_\\').'%';
|
||||
$query->where(fn (Builder $q) => $q->where('summary', 'like', $like)->orWhere('subject_label', 'like', $like)
|
||||
->orWhere('user_name', 'like', $like)->orWhere('email', 'like', $like));
|
||||
}
|
||||
|
||||
$total = (clone $query)->count();
|
||||
$pages = max(1, (int) ceil($total / self::PER_PAGE));
|
||||
$page = min($pages, max(1, $request->integer('page', 1)));
|
||||
$rows = $query->orderByDesc('id')->forPage($page, self::PER_PAGE)->get();
|
||||
|
||||
$banned = array_values(array_filter(IpBan::query()->active()->pluck('ip')->all(), fn (mixed $ip) => is_string($ip) && ! IpBans::isNeverBanned($ip)));
|
||||
$posts = $this->existingPosts($rows->where('subject_type', 'post')->pluck('subject_id')->filter()->all());
|
||||
$day = now()->subDay();
|
||||
|
||||
return response()->json([
|
||||
'entries' => $rows->map(fn (AuditLog $entry) => [
|
||||
'id' => $entry->id,
|
||||
'at' => $entry->created_at->toIso8601String(),
|
||||
'event' => $entry->event,
|
||||
'summary' => $entry->summary,
|
||||
'subject' => $entry->subject_label === null ? null : [
|
||||
'type' => str_replace('_', ' ', (string) $entry->subject_type),
|
||||
'label' => $entry->subject_label,
|
||||
'url' => $entry->subject_type === 'post' && in_array($entry->subject_id, $posts, true)
|
||||
? route(Names::route('posts.edit'), $entry->subject_id, false)
|
||||
: null,
|
||||
],
|
||||
'details' => $entry->details ?? [],
|
||||
'user_id' => $entry->user_id,
|
||||
'who' => $entry->user_name,
|
||||
'email' => $entry->email,
|
||||
'ip' => $entry->ip,
|
||||
'browser' => $entry->user_agent === null ? null : self::browser($entry->user_agent),
|
||||
'user_agent' => $entry->user_agent,
|
||||
'banned' => $entry->ip !== null && in_array($entry->ip, $banned, true),
|
||||
'never_banned' => $entry->ip !== null && IpBans::isNeverBanned($entry->ip),
|
||||
])->values(),
|
||||
'pagination' => ['page' => $page, 'pages' => $pages, 'total' => $total],
|
||||
'filters' => $filters,
|
||||
'accounts' => $this->accounts(),
|
||||
'summary' => [
|
||||
'logins' => AuditLog::query()->where('event', AuditLog::LOGIN)->where('created_at', '>=', $day)->count(),
|
||||
'failed' => AuditLog::query()->where('event', AuditLog::LOGIN_FAILED)->where('created_at', '>=', $day)->count(),
|
||||
'refused' => AuditLog::query()->where('event', AuditLog::REFUSED)->where('created_at', '>=', $day)->count(),
|
||||
'banned' => count($banned),
|
||||
],
|
||||
'bans' => IpBan::query()->orderByDesc('created_at')->get()->map(fn (IpBan $ban) => [
|
||||
'id' => $ban->id,
|
||||
'ip' => $ban->ip,
|
||||
'reason' => $ban->reason,
|
||||
'automatic' => $ban->automatic,
|
||||
'whole_site' => $ban->whole_site,
|
||||
'by' => $ban->user_name,
|
||||
'hits' => $ban->hits,
|
||||
'last_hit_at' => $ban->last_hit_at?->toIso8601String(),
|
||||
'expires_at' => $ban->expires_at?->toIso8601String(),
|
||||
'created_at' => $ban->created_at->toIso8601String(),
|
||||
'active' => $ban->isActive() && ! IpBans::isNeverBanned($ban->ip),
|
||||
])->sortByDesc('active')->values(),
|
||||
// What was written down about addresses, by address. Kept until removed, also after the log is gone.
|
||||
'notes' => IpNote::query()->orderByDesc('updated_at')->get()->map(fn (IpNote $note) => [
|
||||
'ip' => $note->ip,
|
||||
'group' => $note->group_name,
|
||||
'note' => $note->note,
|
||||
'by' => $note->user_name,
|
||||
'updated_at' => $note->updated_at?->toIso8601String(),
|
||||
])->values(),
|
||||
'settings' => AuditSetting::current()->rules(),
|
||||
'max_keep_days' => AuditSetting::maxKeepDays(),
|
||||
'can_manage' => Gate::allows('audit.manage'),
|
||||
'my_ip' => $request->ip(),
|
||||
// The addresses that are never banned (config manager.audit.never_ban): no button for those.
|
||||
'never_banned' => IpBans::neverBanned(),
|
||||
'whole_site_bans' => (bool) config('manager.audit.whole_site_bans'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function ban(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'ip' => ['required', 'ip'],
|
||||
'reason' => ['nullable', 'string', 'max:200'],
|
||||
// 0: until someone lifts it. At most a year.
|
||||
'minutes' => ['required', 'integer', 'min:0', 'max:525600'],
|
||||
// Off the whole site, not only out of the manager.
|
||||
'whole_site' => ['boolean'],
|
||||
]);
|
||||
|
||||
$ip = $request->string('ip')->trim()->toString();
|
||||
|
||||
// Nobody bans the address they are on: the next click would be refused.
|
||||
if ($ip === $request->ip()) {
|
||||
return $this->refuse('ip', 'That is the address you are on yourself.');
|
||||
}
|
||||
|
||||
if (IpBans::isNeverBanned($ip)) {
|
||||
return $this->refuse('ip', 'This address is on the list that is never banned.');
|
||||
}
|
||||
|
||||
$wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans');
|
||||
$reason = $request->string('reason')->trim()->toString();
|
||||
$ban = $this->bans->ban($ip, $reason !== '' ? $reason : null, $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite);
|
||||
|
||||
// Also when the address was banned before: the line of the log is filed under it either way.
|
||||
if ($ban !== null) {
|
||||
$this->trail->about($ban);
|
||||
}
|
||||
|
||||
return response()->json(['message' => $wholeSite ? __(':ip is banned from the whole site.', ['ip' => $ip]) : __(':ip is banned from the manager.', ['ip' => $ip])], 201);
|
||||
}
|
||||
|
||||
public function unban(int $ban): JsonResponse
|
||||
{
|
||||
$ipBan = IpBan::query()->findOrFail($ban);
|
||||
$this->trail->about($ipBan);
|
||||
$this->bans->lift($ipBan);
|
||||
|
||||
return response()->json(['message' => __('The ban of :ip is lifted.', ['ip' => $ipBan->ip])]);
|
||||
}
|
||||
|
||||
/** Bans every address of a group at once, with the same time, reason and reach. */
|
||||
public function banGroup(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'group' => ['required', 'string', 'max:60'],
|
||||
'reason' => ['nullable', 'string', 'max:200'],
|
||||
'minutes' => ['required', 'integer', 'min:0', 'max:525600'],
|
||||
'whole_site' => ['boolean'],
|
||||
]);
|
||||
|
||||
$group = $request->string('group')->trim()->toString();
|
||||
$reason = $request->string('reason')->trim()->toString();
|
||||
$wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans');
|
||||
$banned = 0;
|
||||
$skipped = 0;
|
||||
|
||||
// The line of the log is about the group, not about the first address of it.
|
||||
$this->trail->about(null);
|
||||
|
||||
foreach ($this->addressesOf($group) as $ip) {
|
||||
// The address one is on and the ones that are never banned stay in, as with a ban of one address.
|
||||
$ban = $ip === $request->ip() ? null : $this->bans->ban($ip, $reason !== '' ? $reason : "Group: {$group}", $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite);
|
||||
$ban === null ? $skipped++ : $banned++;
|
||||
}
|
||||
|
||||
if ($banned === 0) {
|
||||
return $this->refuse('group', $skipped === 0
|
||||
? "The group \"{$group}\" has no addresses."
|
||||
: "None of the addresses of \"{$group}\" can be banned: your own and the ones that are never banned stay in.");
|
||||
}
|
||||
|
||||
return response()->json(['message' => sprintf(
|
||||
'%d %s of "%s" banned from %s%s.',
|
||||
$banned,
|
||||
$banned === 1 ? 'address' : 'addresses',
|
||||
$group,
|
||||
$wholeSite ? 'the whole site' : 'the manager',
|
||||
$skipped > 0 ? " ({$skipped} left alone: your own or never banned)" : '',
|
||||
), 'banned' => $banned, 'skipped' => $skipped], 201);
|
||||
}
|
||||
|
||||
/** Lets every address of a group back in. */
|
||||
public function unbanGroup(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate(['group' => ['required', 'string', 'max:60']]);
|
||||
|
||||
$group = $request->string('group')->trim()->toString();
|
||||
$bans = IpBan::query()->whereIn('ip', $this->addressesOf($group))->get();
|
||||
$this->trail->about(null);
|
||||
$bans->each(fn (IpBan $ban) => $this->bans->lift($ban));
|
||||
|
||||
return response()->json(['message' => sprintf('%d %s of "%s" lifted.', $bans->count(), $bans->count() === 1 ? 'ban' : 'bans', $group), 'lifted' => $bans->count()]);
|
||||
}
|
||||
|
||||
/** Writes the note about an address and the group it is in, or removes both when they are left empty. */
|
||||
public function note(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'ip' => ['required', 'ip'],
|
||||
'note' => ['nullable', 'string', 'max:2000'],
|
||||
// Addresses with the same group are banned and let back in together.
|
||||
'group' => ['nullable', 'string', 'max:60'],
|
||||
]);
|
||||
|
||||
$ip = IpNote::spell($request->string('ip')->toString());
|
||||
$text = $request->string('note')->trim()->toString();
|
||||
$group = $request->string('group')->trim()->toString();
|
||||
$note = IpNote::query()->where('ip', $ip)->first();
|
||||
|
||||
if ($text === '' && $group === '') {
|
||||
if ($note !== null) {
|
||||
$this->trail->about($note);
|
||||
$note->delete();
|
||||
}
|
||||
|
||||
return response()->json(['message' => __('The note about :ip is removed.', ['ip' => $ip])]);
|
||||
}
|
||||
|
||||
$note ??= new IpNote(['ip' => $ip]);
|
||||
$user = Auth::user();
|
||||
$name = data_get($user, 'name');
|
||||
$note->fill(['note' => $text, 'group_name' => $group !== '' ? $group : null, 'user_id' => $user?->getAuthIdentifier(), 'user_name' => is_string($name) ? $name : null])->save();
|
||||
$this->trail->about($note);
|
||||
|
||||
return response()->json(['message' => __('The note about :ip is saved.', ['ip' => $ip])]);
|
||||
}
|
||||
|
||||
public function settings(Request $request): JsonResponse
|
||||
{
|
||||
/** @var array<string, mixed> $rules */
|
||||
$rules = $request->validate([
|
||||
'auto_ban' => ['required', 'boolean'],
|
||||
'max_failures' => ['required', 'integer', 'min:3', 'max:100'],
|
||||
'window_minutes' => ['required', 'integer', 'min:1', 'max:1440'],
|
||||
'ban_minutes' => ['required', 'integer', 'min:0', 'max:525600'],
|
||||
// What the site promises about how long the log is kept (config manager.audit.max_keep_days).
|
||||
'keep_days' => ['required', 'integer', 'min:7', 'max:'.AuditSetting::maxKeepDays()],
|
||||
]);
|
||||
|
||||
AuditSetting::current()->forceFill(['id' => 1, ...$rules])->save();
|
||||
|
||||
return response()->json(['message' => __('Rules saved.'), 'settings' => AuditSetting::current()->rules()]);
|
||||
}
|
||||
|
||||
private function refuse(string $field, string $message): JsonResponse
|
||||
{
|
||||
return response()->json(['message' => $message = __($message), 'errors' => [$field => [$message]]], 422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function addressesOf(string $group): array
|
||||
{
|
||||
return array_values(array_filter(IpNote::query()->where('group_name', $group)->orderBy('id')->pluck('ip')->all(), is_string(...)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $ids
|
||||
* @return list<int>
|
||||
*/
|
||||
private function existingPosts(array $ids): array
|
||||
{
|
||||
if ($ids === [] || ! Route::has(Names::route('posts.edit'))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Post::query()->whereIn('id', $ids)->pluck('id')->map(fn ($id) => (int) $id)->all();
|
||||
}
|
||||
|
||||
/** @return list<array{id: mixed, name: mixed}> */
|
||||
private function accounts(): array
|
||||
{
|
||||
/** @var class-string<Model> $model */
|
||||
$model = config('manager.user_model');
|
||||
|
||||
return $model::query()->orderBy('name')->get()->map(fn ($user) => ['id' => $user->getKey(), 'name' => $user->name])->values()->all();
|
||||
}
|
||||
|
||||
/** "Firefox on Linux": enough to recognise a browser; the whole line is there to hover. */
|
||||
private static function browser(string $line): string
|
||||
{
|
||||
$agent = new UserAgent($line);
|
||||
|
||||
if ($agent->isBot()) {
|
||||
return $agent->bot()['name'] ?? 'A program';
|
||||
}
|
||||
|
||||
return $agent->browser().' on '.$agent->os();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Illuminate\Auth\Events\Failed;
|
||||
use Illuminate\Auth\Events\Login;
|
||||
use Illuminate\Auth\Events\Logout;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Contracts\Http\Kernel;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* The audit log and the bans: who logged in or failed to, who did what in the manager, and the
|
||||
* addresses that are kept out. Off by default: it stores addresses and browser lines, so a site
|
||||
* switches it on knowingly (and says so in its privacy policy).
|
||||
*/
|
||||
class AuditModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'audit';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Audit log';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['audit_logs', 'ip_bans', 'audit_settings', 'ip_notes'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('audit.view', 'See the audit log: who logged in and what was done, with addresses and browsers', 'Audit log'),
|
||||
new Permission('audit.manage', 'Ban addresses and lift bans, write notes about addresses, and set the rules of the audit log', 'Audit log', needs: ['audit.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Audit log', 'section' => 'Administration', 'route' => Names::route('audit.index'), 'permission' => 'audit.view']];
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [PruneAuditLog::class, LiftBan::class];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'audit.bans.store' => ['Banned an address', ['reason', 'whole_site']],
|
||||
'audit.bans.destroy' => ['Lifted the ban of an address'],
|
||||
'audit.groups.ban' => ['Banned the addresses of a group', ['group', 'reason', 'whole_site']],
|
||||
'audit.groups.unban' => ['Lifted the bans of a group', ['group']],
|
||||
'audit.notes.update' => ['Wrote or removed the note about an address', ['ip', 'group']],
|
||||
'audit.settings' => ['Changed the rules of the audit log'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['audit.index' => 'Opened the audit log'];
|
||||
}
|
||||
|
||||
/** A banned address is refused before the session starts; every request of a manager account is written down. */
|
||||
public function middleware(): array
|
||||
{
|
||||
return ['before' => [RefuseBannedAddress::class], 'after' => [RecordActions::class]];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
app()->singleton(IpBans::class);
|
||||
|
||||
app('router')->aliasMiddleware('manager.not-banned', RefuseBannedAddress::class);
|
||||
|
||||
// The first thing a request makes is what the line of the log is about.
|
||||
Event::listen('eloquent.created: *', function (string $event, array $data) {
|
||||
if (($data[0] ?? null) instanceof Model) {
|
||||
app(AuditTrail::class)->made($data[0]);
|
||||
}
|
||||
});
|
||||
|
||||
$this->listenForLogins();
|
||||
|
||||
if (config('manager.audit.whole_site_bans') && ($kernel = app(Kernel::class)) && method_exists($kernel, 'pushMiddleware')) {
|
||||
$kernel->pushMiddleware(RefuseBannedFromTheSite::class);
|
||||
}
|
||||
|
||||
// Only the console runs the schedule; a web request never needs to resolve it.
|
||||
if (app()->runningInConsole()) {
|
||||
app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(PruneAuditLog::class)->dailyAt('03:40'));
|
||||
}
|
||||
}
|
||||
|
||||
/** The host owns the login: Laravel's own events say what happened, whatever the login looks like. */
|
||||
private function listenForLogins(): void
|
||||
{
|
||||
$model = config('manager.user_model');
|
||||
|
||||
Event::listen(Login::class, function (Login $event) use ($model) {
|
||||
if ($event->user instanceof $model) {
|
||||
app(AuditTrail::class)->record(AuditLog::LOGIN, __('Logged in'), $event->user);
|
||||
}
|
||||
});
|
||||
|
||||
Event::listen(Logout::class, function (Logout $event) use ($model) {
|
||||
if ($event->user instanceof $model) {
|
||||
app(AuditTrail::class)->record(AuditLog::LOGOUT, __('Logged out'), $event->user);
|
||||
}
|
||||
});
|
||||
|
||||
Event::listen(Failed::class, function (Failed $event) {
|
||||
$email = $event->credentials['email'] ?? null;
|
||||
$email = is_string($email) ? $email : null;
|
||||
|
||||
app(AuditTrail::class)->record(
|
||||
AuditLog::LOGIN_FAILED,
|
||||
$event->user === null ? 'Failed login: no such account' : 'Failed login: wrong password',
|
||||
$event->user,
|
||||
email: $email,
|
||||
);
|
||||
|
||||
app(IpBans::class)->afterFailedLogin(request()->ip());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Models\AuditSetting;
|
||||
use IriksIT\Manager\Models\IpBan;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Addresses that are kept out of the manager (the login page included; the public site stays
|
||||
* open to them), and the only code that writes the bans. A ban is given by hand, or by itself
|
||||
* after too many failed logins from one address (the rules are in AuditSetting). A ban by hand can
|
||||
* be for the whole site (config `manager.audit.whole_site_bans`); a ban by itself never is.
|
||||
*
|
||||
* Who locked themselves out lifts the ban on the server: `php artisan manager:unban`.
|
||||
*/
|
||||
final class IpBans
|
||||
{
|
||||
private const WHOLE_SITE = 'manager.ip-bans.whole-site';
|
||||
|
||||
public function __construct(private readonly AuditTrail $trail) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function neverBanned(): array
|
||||
{
|
||||
$addresses = config('manager.audit.never_ban');
|
||||
|
||||
return is_array($addresses) ? array_values(array_filter($addresses, is_string(...))) : [];
|
||||
}
|
||||
|
||||
/** Compared in packed form: an IPv6 address has more than one spelling. */
|
||||
public static function isNeverBanned(string $ip): bool
|
||||
{
|
||||
$packed = @inet_pton($ip);
|
||||
|
||||
foreach (self::neverBanned() as $address) {
|
||||
if ($address === $ip || ($packed !== false && @inet_pton($address) === $packed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The ban that keeps this address out of the manager now, if any. */
|
||||
public function for(?string $ip): ?IpBan
|
||||
{
|
||||
return $ip === null || self::isNeverBanned($ip) ? null : IpBan::query()->active()->where('ip', $ip)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ban that keeps this address off the whole site now, if any. Asked at every request of
|
||||
* every visitor, so the list (address => id) comes from the cache; it is thrown away whenever
|
||||
* a ban is saved or deleted (see IpBan).
|
||||
*/
|
||||
public function wholeSite(?string $ip): ?IpBan
|
||||
{
|
||||
if ($ip === null || self::isNeverBanned($ip)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$banned = Cache::get(self::WHOLE_SITE);
|
||||
|
||||
if (! is_array($banned)) {
|
||||
// Not kept while the table is not there yet: the answer would outlive the migration.
|
||||
if (! self::ready()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$banned = IpBan::query()->where('whole_site', true)->pluck('id', 'ip')->all();
|
||||
Cache::forever(self::WHOLE_SITE, $banned);
|
||||
}
|
||||
|
||||
if (! isset($banned[$ip])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only now the database: whether it still counts (a ban ends by itself).
|
||||
return IpBan::query()->active()->where('whole_site', true)->where('ip', $ip)->first();
|
||||
}
|
||||
|
||||
public static function forgetWholeSite(): void
|
||||
{
|
||||
Cache::forget(self::WHOLE_SITE);
|
||||
}
|
||||
|
||||
private static function ready(): bool
|
||||
{
|
||||
try {
|
||||
return Schema::hasTable((new IpBan)->getTable());
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* $minutes 0: until someone lifts it. Null for an address that is never banned.
|
||||
*/
|
||||
public function ban(string $ip, ?string $reason, int $minutes, ?Authenticatable $by, bool $automatic = false, bool $wholeSite = false): ?IpBan
|
||||
{
|
||||
if (self::isNeverBanned($ip)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$name = $by === null ? null : data_get($by, 'name');
|
||||
|
||||
return IpBan::query()->updateOrCreate(['ip' => $ip], [
|
||||
'reason' => $reason,
|
||||
'automatic' => $automatic,
|
||||
'whole_site' => $wholeSite,
|
||||
'user_id' => $by?->getAuthIdentifier(),
|
||||
'user_name' => is_string($name) ? $name : null,
|
||||
'hits' => 0,
|
||||
'last_hit_at' => null,
|
||||
'expires_at' => $minutes > 0 ? now()->addMinutes($minutes) : null,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function lift(IpBan $ban): void
|
||||
{
|
||||
$ban->delete();
|
||||
}
|
||||
|
||||
/** A banned address knocked: only counted, so a flood does not fill the log. */
|
||||
public function knocked(IpBan $ban): void
|
||||
{
|
||||
IpBan::query()->whereKey($ban->id)->update(['hits' => $ban->hits + 1, 'last_hit_at' => now()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* After a failed login: bans the address when it failed too often. What counts are the
|
||||
* failures since the address last logged in or was last banned or let back in, so a ban that
|
||||
* was lifted does not come back at the next typo.
|
||||
*/
|
||||
public function afterFailedLogin(?string $ip): ?IpBan
|
||||
{
|
||||
$rules = AuditSetting::current()->rules();
|
||||
|
||||
if ($ip === null || ! $rules['auto_ban'] || self::isNeverBanned($ip) || $this->for($ip) !== null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// By id and not by time: a login in the same second as the failure before it still comes after it.
|
||||
$reset = AuditLog::query()
|
||||
->where(fn (Builder $query) => $query
|
||||
->where(fn (Builder $q) => $q->where('event', AuditLog::LOGIN)->where('ip', $ip))
|
||||
->orWhere(fn (Builder $q) => $q->where('subject_type', 'ip_ban')->where('subject_label', $ip)))
|
||||
->max('id');
|
||||
|
||||
$failures = AuditLog::query()
|
||||
->where('event', AuditLog::LOGIN_FAILED)
|
||||
->where('ip', $ip)
|
||||
->where('id', '>', is_numeric($reset) ? (int) $reset : 0)
|
||||
->where('created_at', '>=', now()->subMinutes($rules['window_minutes']))
|
||||
->count();
|
||||
|
||||
if ($failures < $rules['max_failures']) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ban = $this->ban($ip, sprintf('%d failed logins within %d minutes', $failures, $rules['window_minutes']), $rules['ban_minutes'], null, automatic: true);
|
||||
|
||||
if ($ban === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->trail->record(AuditLog::BAN, __('The address was banned after too many failed logins'), subject: $ban, details: ['failures' => $failures]);
|
||||
|
||||
return $ban;
|
||||
}
|
||||
|
||||
/** Bans that ended before $before are deleted; returns how many. */
|
||||
public function forgetExpiredBefore(Carbon $before): int
|
||||
{
|
||||
$ended = IpBan::query()->whereNotNull('expires_at')->where('expires_at', '<', $before);
|
||||
$count = $ended->count();
|
||||
$ended->delete();
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Models\IpBan;
|
||||
|
||||
/** The way back in for who is locked out by a ban on their own address: it is lifted on the server. */
|
||||
class LiftBan extends Command
|
||||
{
|
||||
protected $signature = 'manager:unban {ip? : The address to let back in; without it all bans are listed} {--all : Lift every ban}';
|
||||
|
||||
protected $description = 'Lift the ban of an address';
|
||||
|
||||
public function handle(IpBans $bans): int
|
||||
{
|
||||
$ip = $this->argument('ip');
|
||||
|
||||
if ($this->option('all')) {
|
||||
$lifted = IpBan::query()->get()->each(fn (IpBan $ban) => $bans->lift($ban))->count();
|
||||
$this->line("{$lifted} ban(s) lifted.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if (! is_string($ip)) {
|
||||
$rows = IpBan::query()->orderBy('ip')->get()->map(fn (IpBan $ban) => [
|
||||
$ban->ip,
|
||||
$ban->isActive() ? ($ban->expires_at?->format('Y-m-d H:i') ?? 'until lifted') : 'ended',
|
||||
$ban->reason ?? '',
|
||||
])->all();
|
||||
|
||||
$rows === [] ? $this->line('No address is banned.') : $this->table(['Address', 'Until', 'Reason'], $rows);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$ban = IpBan::query()->where('ip', $ip)->first();
|
||||
|
||||
if ($ban === null) {
|
||||
$this->error("{$ip} is not banned.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$bans->lift($ban);
|
||||
$this->line("The ban of {$ip} is lifted.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Models\AuditSetting;
|
||||
|
||||
class PruneAuditLog extends Command
|
||||
{
|
||||
protected $signature = 'manager:audit-prune';
|
||||
|
||||
protected $description = 'Delete the lines of the audit log and the ended bans that are older than the rules keep them';
|
||||
|
||||
public function handle(IpBans $bans): int
|
||||
{
|
||||
$before = now()->subDays(AuditSetting::current()->rules()['keep_days']);
|
||||
|
||||
$old = AuditLog::query()->where('created_at', '<', $before);
|
||||
$lines = $old->count();
|
||||
$old->delete();
|
||||
|
||||
$this->line(sprintf('%d line(s) of the audit log and %d ended ban(s) deleted.', $lines, $bans->forgetExpiredBefore($before)));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use BackedEnum;
|
||||
use Closure;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Writes down what an account does in the manager: one line for every request that changes
|
||||
* something and went through, one for every page that is opened, and one for everything the
|
||||
* account was not allowed to do. It sits behind the login on all manager routes, so a new route
|
||||
* is in the log without anyone thinking of it; the modules give routes a readable name
|
||||
* (Module::actions() and Module::views()).
|
||||
*/
|
||||
class RecordActions
|
||||
{
|
||||
/** Opening the same page again within this time is not a new line. */
|
||||
private const SAME_LOOK_MINUTES = 5;
|
||||
|
||||
/** Requests that only look at something while it is written: not an action, not worth a line. */
|
||||
private const SILENT = ['markdown.preview'];
|
||||
|
||||
public function __construct(private readonly AuditTrail $trail, private readonly ModuleRegistry $modules) {}
|
||||
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$user = Auth::user();
|
||||
$this->trail->reset();
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($user !== null) {
|
||||
$this->write($request, $response, $user, $this->trail->firstMade());
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function write(Request $request, Response $response, Authenticatable $user, ?Model $subject): void
|
||||
{
|
||||
$route = Str::after((string) $request->route()?->getName(), Names::routePrefix());
|
||||
$actions = $this->modules->actions();
|
||||
$views = $this->modules->views();
|
||||
$thrown = property_exists($response, 'exception') && $response->exception instanceof Throwable ? $response->exception : null;
|
||||
$details = $this->details($request, $actions[$route][1] ?? []);
|
||||
$name = $actions[$route][0] ?? ($views[$route] ?? '');
|
||||
$name = $name !== '' ? __($name) : __('Asked for :request', ['request' => $request->method().' /'.ltrim($request->path(), '/')]);
|
||||
|
||||
if (in_array($route, self::SILENT, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($thrown !== null) {
|
||||
// Only a refusal is worth a line; a form with a mistake or a page that is not there is not.
|
||||
if ($thrown instanceof AuthorizationException || ($thrown instanceof HttpExceptionInterface && $thrown->getStatusCode() === 403)) {
|
||||
$this->trail->record(AuditLog::REFUSED, __('Was not allowed: :what', ['what' => Str::lcfirst($name)]), $user, $subject, $details, $route);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($response->getStatusCode() >= 400) {
|
||||
return;
|
||||
}
|
||||
|
||||
$changes = ! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true);
|
||||
|
||||
if (! $changes && ! isset($actions[$route])) {
|
||||
$this->viewed($user, $route, __($views[$route] ?? ''), $subject, $details);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->trail->record(AuditLog::ACTION, $name, $user, $subject, $details, $route);
|
||||
}
|
||||
|
||||
/**
|
||||
* A page that was opened. Not twice in a row: filtering a list or loading a page again within
|
||||
* a few minutes is the same look. A route with an empty name stays silent (what a page asks
|
||||
* for in the background).
|
||||
*
|
||||
* @param array<string, mixed> $details
|
||||
*/
|
||||
private function viewed(Authenticatable $user, string $route, string $summary, ?Model $subject, array $details): void
|
||||
{
|
||||
if ($summary === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$last = AuditLog::query()->where('user_id', $user->getAuthIdentifier())->orderByDesc('id')->first();
|
||||
$about = $subject === null ? null : AuditTrail::describe($subject);
|
||||
|
||||
if ($last !== null && $last->event === AuditLog::VIEWED && $last->action === $route
|
||||
&& $last->subject_id === ($about['id'] ?? null) && ($last->details ?? []) === $details
|
||||
&& $last->created_at->gt(now()->subMinutes(self::SAME_LOOK_MINUTES))) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->trail->record(AuditLog::VIEWED, $summary, $user, $subject, $details, $route);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the address names (`/posts/5`) and the fields of the form a module said may be kept.
|
||||
*
|
||||
* @param list<string> $kept
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function details(Request $request, array $kept): array
|
||||
{
|
||||
$input = [];
|
||||
|
||||
foreach ($request->route()?->parameters() ?? [] as $name => $parameter) {
|
||||
$value = $parameter instanceof BackedEnum ? $parameter->value : $parameter;
|
||||
|
||||
if (is_scalar($value) && ! is_bool($value) && $name !== 'type') {
|
||||
$input[$name] = Str::limit((string) $value, 100, '…');
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($kept as $field) {
|
||||
$value = $request->input($field);
|
||||
|
||||
if (is_bool($value)) {
|
||||
$value = $value ? 'yes' : 'no';
|
||||
}
|
||||
|
||||
if (is_string($value) && $value !== '') {
|
||||
$input[$field] = Str::limit($value, 100, '…');
|
||||
}
|
||||
}
|
||||
|
||||
return $input === [] ? [] : ['input' => $input];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Models\IpBan;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Keeps a banned address out of the whole manager, the login page included. It runs ahead of the
|
||||
* session and the login, so a banned visitor is not sent round in circles. The answer is written
|
||||
* here and not thrown. Alias `manager.not-banned`: put it on the login routes of the host app too.
|
||||
*/
|
||||
class RefuseBannedAddress
|
||||
{
|
||||
public function __construct(private readonly IpBans $bans) {}
|
||||
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$ban = $this->bans->for($request->ip());
|
||||
|
||||
if ($ban === null) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$this->bans->knocked($ban);
|
||||
|
||||
return self::answer($request, $ban);
|
||||
}
|
||||
|
||||
/** The page (or JSON) a banned address gets, also for a ban on the whole site. */
|
||||
public static function answer(Request $request, IpBan $ban): Response
|
||||
{
|
||||
$where = $ban->whole_site ? __('this site') : __('the manager');
|
||||
$message = $ban->expires_at === null
|
||||
? __('This address is blocked from :where.', ['where' => $where])
|
||||
: __('This address is blocked from :where until :when.', ['where' => $where, 'when' => $ban->expires_at->format('j F Y, H:i')]);
|
||||
|
||||
// A ban that followed too many attempts is "429 Too Many Requests" and says when to come
|
||||
// back; one that was given by hand is a plain "403 Forbidden".
|
||||
$status = $ban->automatic ? 429 : 403;
|
||||
$headers = ['Cache-Control' => 'no-store'];
|
||||
|
||||
if ($ban->automatic && $ban->expires_at !== null) {
|
||||
$headers['Retry-After'] = (string) max(1, (int) now()->diffInSeconds($ban->expires_at, false));
|
||||
}
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json(['message' => $message], $status, $headers)
|
||||
: response()->view('manager::banned', ['message' => $message, 'status' => $status], $status, $headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Audit;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Keeps an address with a ban "for the whole site" away from everything. Only added when
|
||||
* `manager.audit.whole_site_bans` is on. It runs for every request, so the question is answered
|
||||
* from the cache (IpBans::wholeSite) and costs a visitor nothing.
|
||||
*/
|
||||
class RefuseBannedFromTheSite
|
||||
{
|
||||
public function __construct(private readonly IpBans $bans) {}
|
||||
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$ban = $this->bans->wholeSite($request->ip());
|
||||
|
||||
if ($ban === null) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$this->bans->knocked($ban);
|
||||
|
||||
return RefuseBannedAddress::answer($request, $ban);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
|
||||
// Who did what in the manager, and every attempt to log in. A row stands on its own: the
|
||||
// name of the account is copied, so it stays readable after the account is deleted.
|
||||
Tables::create(Names::table('audit_logs'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('event', 40)->index();
|
||||
// The route that was called, for an action in the manager.
|
||||
$table->string('action', 100)->nullable();
|
||||
$table->string('summary');
|
||||
$table->string('subject_type', 40)->nullable();
|
||||
$table->unsignedBigInteger('subject_id')->nullable();
|
||||
$table->string('subject_label')->nullable();
|
||||
$table->json('details')->nullable();
|
||||
$table->unsignedBigInteger('user_id')->nullable()->index();
|
||||
$table->string('user_name')->nullable();
|
||||
// The address that was typed at a login that failed.
|
||||
$table->string('email')->nullable();
|
||||
$table->string('ip', 45)->nullable()->index();
|
||||
$table->string('user_agent', 500)->nullable();
|
||||
$table->dateTime('created_at')->index();
|
||||
});
|
||||
|
||||
// Addresses that are kept out of the manager, or off the whole site.
|
||||
Tables::create(Names::table('ip_bans'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('ip', 45)->unique();
|
||||
$table->string('reason')->nullable();
|
||||
$table->boolean('automatic')->default(false);
|
||||
$table->boolean('whole_site')->default(false);
|
||||
$table->unsignedBigInteger('user_id')->nullable();
|
||||
$table->string('user_name')->nullable();
|
||||
// How often the address knocked while it was banned.
|
||||
$table->unsignedInteger('hits')->default(0);
|
||||
$table->timestamp('last_hit_at')->nullable();
|
||||
// Null: until someone lifts it.
|
||||
$table->timestamp('expires_at')->nullable();
|
||||
$table->dateTime('created_at');
|
||||
});
|
||||
|
||||
// One row (id 1) with the rules; without it the defaults of the model count.
|
||||
Tables::create(Names::table('audit_settings'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->boolean('auto_ban')->default(true);
|
||||
$table->unsignedSmallInteger('max_failures')->default(10);
|
||||
$table->unsignedSmallInteger('window_minutes')->default(30);
|
||||
$table->unsignedInteger('ban_minutes')->default(1440);
|
||||
$table->unsignedSmallInteger('keep_days')->default(90);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Tables::create(Names::table('ip_notes'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('ip', 45)->unique();
|
||||
// Addresses that belong together carry the same name here; null: no group.
|
||||
$table->string('group_name', 60)->nullable()->index();
|
||||
$table->text('note');
|
||||
$table->unsignedBigInteger('user_id')->nullable();
|
||||
$table->string('user_name')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
|
||||
foreach (['ip_notes', 'audit_settings', 'ip_bans', 'audit_logs'] as $table) {
|
||||
Schema::dropIfExists(Names::table($table));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Audit\AuditController;
|
||||
|
||||
Route::get('/audit', [AuditController::class, 'index'])->name('audit.index')->middleware('can:audit.view');
|
||||
|
||||
Route::middleware('can:audit.manage')->group(function () {
|
||||
Route::post('/audit/bans', [AuditController::class, 'ban'])->name('audit.bans.store');
|
||||
Route::delete('/audit/bans/{ban}', [AuditController::class, 'unban'])->name('audit.bans.destroy')->whereNumber('ban');
|
||||
Route::post('/audit/groups/ban', [AuditController::class, 'banGroup'])->name('audit.groups.ban');
|
||||
Route::post('/audit/groups/unban', [AuditController::class, 'unbanGroup'])->name('audit.groups.unban');
|
||||
Route::put('/audit/notes', [AuditController::class, 'note'])->name('audit.notes.update');
|
||||
Route::put('/audit/settings', [AuditController::class, 'settings'])->name('audit.settings');
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules;
|
||||
|
||||
use IriksIT\Manager\Contracts\Module;
|
||||
|
||||
/**
|
||||
* Convention over configuration: a module `Foo` lives in src/Modules/Foo, with
|
||||
* routes.php and a migrations/ folder next to its class when it needs them.
|
||||
*/
|
||||
abstract class BaseModule implements Module
|
||||
{
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function requires(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function routes(): ?string
|
||||
{
|
||||
return $this->path('routes.php');
|
||||
}
|
||||
|
||||
public function publicRoutes(): ?string
|
||||
{
|
||||
return $this->path('public-routes.php');
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tables (without the prefix) this module needs; `manager:doctor` checks that they exist.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function tables(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps this module adds to the tour. Each: `title` and `text` (English, translated through `__()`), an optional `image` (one of
|
||||
* the pictures of the tour, `MascotController::NAMES`), `menu` (the short route name of a menu item to point at, like `reviews.index`)
|
||||
* and `permission` (the step is left out for an account without it). The contract `Module` does not know this: a module without it adds none.
|
||||
*
|
||||
* @return list<array{title: string, text: string, image?: string, menu?: string, permission?: string}>
|
||||
*/
|
||||
public function tutorial(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function middleware(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function boot(): void {}
|
||||
|
||||
public function migrations(): ?string
|
||||
{
|
||||
return $this->path('migrations');
|
||||
}
|
||||
|
||||
private function path(string $name): ?string
|
||||
{
|
||||
$path = dirname((new \ReflectionClass($this))->getFileName()).'/'.$name;
|
||||
|
||||
return file_exists($path) ? $path : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Costs;
|
||||
|
||||
use IriksIT\Manager\Support\Changelog;
|
||||
use IriksIT\Manager\Support\Costs\Ledger;
|
||||
|
||||
class CostsController
|
||||
{
|
||||
public function index(Ledger $ledger)
|
||||
{
|
||||
$items = $ledger->items();
|
||||
$dates = [];
|
||||
|
||||
foreach (Changelog::releases(limit: 200) as $release) {
|
||||
$dates[$release['version']] = $release['date'];
|
||||
}
|
||||
|
||||
// A group per release, newest first as in the changelog, and before them the work that has no release yet. A row without a
|
||||
// version belongs to the newest release when the site says so (on the live site everything that is deployed is released, and
|
||||
// the row only has no version because the file is filled in afterwards).
|
||||
$groups = [];
|
||||
|
||||
foreach ($dates as $version => $date) {
|
||||
$groups[$version] = ['version' => $version, 'date' => $date, 'items' => []];
|
||||
}
|
||||
|
||||
$newest = config('manager.costs.assign_open_to_newest') ? array_key_first($groups) : null;
|
||||
$open = ['version' => null, 'date' => null, 'items' => []];
|
||||
|
||||
foreach ($items as $item) {
|
||||
if ($item['version'] === null && $newest !== null) {
|
||||
$groups[$newest]['items'][] = $item;
|
||||
} elseif ($item['version'] === null) {
|
||||
$open['items'][] = $item;
|
||||
} else {
|
||||
// A row can name a release the changelog does not have (yet): it still gets its group.
|
||||
$groups[$item['version']] ??= ['version' => $item['version'], 'date' => null, 'items' => []];
|
||||
$groups[$item['version']]['items'][] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
$all = array_values(array_filter([...($open['items'] !== [] ? [$open] : []), ...array_values($groups)], fn (array $group) => $group['items'] !== []));
|
||||
|
||||
$sum = fn (array $rows, string $key): float => (float) array_sum(array_map(fn (array $item) => $item[$key] ?? 0.0, $rows));
|
||||
$hosting = $ledger->hosting();
|
||||
$discount = $ledger->discount();
|
||||
$discounted = round(array_sum(array_map(fn (array $item) => $ledger->discountOn($item), $items)), 2);
|
||||
$work = round($sum($items, 'work_eur'), 2);
|
||||
$ai = round($sum($items, 'eur'), 2);
|
||||
|
||||
return response()->json([
|
||||
'groups' => array_map(fn (array $group) => $group + [
|
||||
'eur' => round($sum($group['items'], 'eur'), 2),
|
||||
'tokens' => (int) $sum($group['items'], 'tokens'),
|
||||
'hours' => round($sum($group['items'], 'hours'), 2),
|
||||
'work_eur' => round($sum($group['items'], 'work_eur'), 2),
|
||||
], $all),
|
||||
// Three costs, kept apart: the work (hours at the hourly rate), what the AI model cost in tokens, and hosting.
|
||||
'costs' => [
|
||||
'hourly_rate' => $ledger->hourlyRate(),
|
||||
'hours' => round($sum($items, 'hours'), 2),
|
||||
'work_eur' => $work,
|
||||
'ai_eur' => $ai,
|
||||
'hosting' => $hosting,
|
||||
'total_eur' => round($work + $ai + $hosting['eur'], 2),
|
||||
'discount' => $discount !== null ? $discount + ['eur' => $discounted] : null,
|
||||
// Never a cent below zero through rounding, and never "-0".
|
||||
'due_eur' => max(0.0, round($work + $ai + $hosting['eur'] - $discounted, 2)) + 0.0,
|
||||
'without_hours' => count(array_filter($items, fn (array $item) => $item['hours'] === null)),
|
||||
],
|
||||
'totals' => [
|
||||
'tokens' => (int) $sum($items, 'tokens'),
|
||||
'steps' => (int) $sum($items, 'steps'),
|
||||
'unpriced' => count(array_filter($items, fn (array $item) => $item['eur'] === null)),
|
||||
],
|
||||
// Where the amounts come from: a price source that was asked once and kept, the fixed rates of the config, or both.
|
||||
'source' => self::source($items),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param list<array{priced_by: string|null}> $items */
|
||||
private static function source(array $items): string
|
||||
{
|
||||
$by = array_values(array_unique(array_filter(array_column($items, 'priced_by'))));
|
||||
|
||||
return match (true) {
|
||||
$by === ['service'] => 'service',
|
||||
in_array('service', $by, true) => 'mixed',
|
||||
default => 'config',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Costs;
|
||||
|
||||
use IriksIT\Manager\Console\CostsPriceCommand;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* What the work on the site has cost: the pieces of work of its `TOKENS.md` with the tokens of each in euros, next to the hours at an
|
||||
* hourly rate, hosting and a discount. For the owner of the site; the prices come from a price source (see `Support\Costs\Ledger`).
|
||||
*/
|
||||
class CostsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'costs';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Costs';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['work_costs'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [new Permission('costs.view', 'See what the work on the site has cost', 'Site')];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'What it cost', 'section' => 'Project', 'route' => Names::route('costs.index'), 'permission' => 'costs.view', 'simple' => true, 'hint' => 'What was built, and what it cost']];
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [CostsPriceCommand::class];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['costs.index' => 'Opened the costs'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::create(Names::table('work_costs'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
// What makes a row the row it is: the day, the model and the tokens (see Support\Costs\Ledger).
|
||||
$table->string('fingerprint', 64)->unique();
|
||||
$table->string('date', 10);
|
||||
$table->string('name');
|
||||
$table->string('version', 40)->nullable();
|
||||
$table->string('model', 80);
|
||||
$table->decimal('usd', 12, 4);
|
||||
$table->decimal('eur', 12, 2);
|
||||
$table->decimal('usd_per_eur', 10, 4);
|
||||
$table->dateTime('priced_at');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('work_costs'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Costs\CostsController;
|
||||
|
||||
Route::get('/costs', [CostsController::class, 'index'])->name('costs.index')->middleware('can:costs.view');
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Leads;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Support\Leads\Intake;
|
||||
use IriksIT\Manager\Support\Leads\Phone;
|
||||
use IriksIT\Manager\Support\Leads\Report;
|
||||
use IriksIT\Manager\Support\Login\Turnstile;
|
||||
|
||||
/**
|
||||
* The one place the forms of the public site are sent to (`manager.leads.form`). A form is a name (the last part of the address) with a
|
||||
* kind and the fields it requires; the questions and moments a visitor may tap are the site's own list, anything else is dropped.
|
||||
*
|
||||
* A form never tells a sender that it was taken for spam: whatever the screening thinks, the visitor gets the normal thank-you. A program
|
||||
* that fills the honeypot field gets it too, and nothing is stored or mailed.
|
||||
*/
|
||||
class LeadFormController
|
||||
{
|
||||
public function store(Request $request, Intake $intake, string $form): JsonResponse|RedirectResponse
|
||||
{
|
||||
$definition = (array) (config('manager.leads.form.forms')[$form] ?? abort(404));
|
||||
$kind = (string) ($definition['kind'] ?? $form);
|
||||
|
||||
// Real visitors never see or fill the honeypot.
|
||||
$honeypot = (string) config('manager.leads.form.honeypot', 'website');
|
||||
if ($honeypot !== '' && $request->filled($honeypot)) {
|
||||
return $this->thanks($request);
|
||||
}
|
||||
|
||||
$attributes = $this->validated($request, (array) ($definition['require'] ?? ['name']));
|
||||
|
||||
// After the fields are right, so the visitor fixes those first: a token works once.
|
||||
if (config('manager.leads.form.turnstile', true) && Turnstile::configured() && ! Turnstile::passes($request->string('turnstile')->limit(2048, '')->toString(), (string) $request->ip())) {
|
||||
throw ValidationException::withMessages(['turnstile' => __('Prove you are not a program, then send it again.')]);
|
||||
}
|
||||
|
||||
$intake->take(
|
||||
[...$attributes, 'kind' => $kind, 'about' => $kind !== 'callback' && $request->string('about')->toString() === 'other' ? 'other' : 'job', 'page' => $this->pageOf($request), 'answers' => $this->answers($request, $kind)],
|
||||
Intake::secondsOpen($request->string('form_token')->toString()),
|
||||
(string) $request->ip(),
|
||||
(string) $request->userAgent(),
|
||||
);
|
||||
|
||||
return $this->thanks($request);
|
||||
}
|
||||
|
||||
/** A tap on the phone number or the WhatsApp button, counted for the page it was on. */
|
||||
public function tap(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['kind' => ['required', 'in:call,whatsapp'], 'path' => ['required', 'string', 'max:255']]);
|
||||
Report::tap($data['kind'], parse_url($data['path'], PHP_URL_PATH) ?: '/');
|
||||
|
||||
return response()->json(['ok' => true], 201);
|
||||
}
|
||||
|
||||
/** A signed moment for a form that is built by script: sent back with the form, it tells how long the form was open. */
|
||||
public function token(): JsonResponse
|
||||
{
|
||||
return response()->json(['token' => Intake::formToken()])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
private function thanks(Request $request): JsonResponse|RedirectResponse
|
||||
{
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['ok' => true], 201);
|
||||
}
|
||||
|
||||
$to = config('manager.leads.form.thanks');
|
||||
|
||||
return ($to ? redirect($to) : back())->with('manager_lead_sent', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $require `name`, `phone`, `email`, `contact` (one box: with an @ a mail address, else a phone number), `message`, `location`, `subject`
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function validated(Request $request, array $require): array
|
||||
{
|
||||
$needs = fn (string $field) => in_array($field, $require, true) ? ['required'] : ['nullable'];
|
||||
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
'contact' => [...$needs('contact'), 'string', 'max:255'],
|
||||
'phone' => [...$needs('phone'), 'string', 'max:40'],
|
||||
'email' => [...$needs('email'), 'email', 'max:255'],
|
||||
'message' => [...$needs('message'), 'string', 'max:5000'],
|
||||
'location' => [...$needs('location'), 'string', 'max:120'],
|
||||
'about' => ['nullable', 'in:job,other'],
|
||||
'prefers' => ['nullable', 'in:phone,whatsapp,email'],
|
||||
'subject' => [...$needs('subject'), 'string', 'max:255'],
|
||||
'subject_id' => ['nullable', 'integer'],
|
||||
]);
|
||||
|
||||
$phone = $request->string('phone')->trim()->toString();
|
||||
$email = $request->string('email')->trim()->toString();
|
||||
$contact = $request->string('contact')->trim()->toString();
|
||||
|
||||
if ($contact !== '') {
|
||||
if (str_contains($contact, '@')) {
|
||||
filter_var($contact, FILTER_VALIDATE_EMAIL) !== false || throw ValidationException::withMessages(['contact' => __('This does not look like a mail address.')]);
|
||||
$email = $contact;
|
||||
} else {
|
||||
$phone = $contact;
|
||||
}
|
||||
}
|
||||
|
||||
if ($phone !== '' && Phone::international($phone) === null) {
|
||||
throw ValidationException::withMessages([$contact !== '' ? 'contact' : 'phone' => __('This does not look like a phone number.')]);
|
||||
}
|
||||
|
||||
if ($phone === '' && $email === '') {
|
||||
throw ValidationException::withMessages([in_array('contact', $require, true) ? 'contact' : 'phone' => __('Give a phone number or a mail address, so we can answer.')]);
|
||||
}
|
||||
|
||||
return [
|
||||
'name' => $request->string('name')->trim()->toString(),
|
||||
'phone' => $phone !== '' ? $phone : null,
|
||||
'email' => $email !== '' ? $email : null,
|
||||
'prefers' => $request->filled('prefers') ? $request->string('prefers')->toString() : null,
|
||||
'message' => $request->filled('message') ? $request->string('message')->trim()->toString() : null,
|
||||
'location' => $request->filled('location') ? $request->string('location')->trim()->toString() : null,
|
||||
'subject' => $request->filled('subject') ? $request->string('subject')->trim()->toString() : null,
|
||||
'subject_id' => $request->filled('subject_id') ? $request->integer('subject_id') : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* What was tapped: only the questions and the moments the site itself offers.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function answers(Request $request, string $kind): array
|
||||
{
|
||||
$answers = [];
|
||||
$moment = $request->string('moment')->toString();
|
||||
$moments = (array) config('manager.leads.form.moments', []);
|
||||
|
||||
if ($kind === 'callback' && in_array($moment, $moments, true)) {
|
||||
$answers[__('When suits you?')] = $moment;
|
||||
}
|
||||
|
||||
foreach ((array) config('manager.leads.form.questions', []) as $key => $question) {
|
||||
$answer = $request->string("answers.{$key}")->toString();
|
||||
|
||||
if ($answer !== '' && in_array($answer, (array) ($question['options'] ?? []), true)) {
|
||||
$answers[(string) ($question['label'] ?? $key)] = $answer;
|
||||
}
|
||||
}
|
||||
|
||||
return $answers;
|
||||
}
|
||||
|
||||
/** The page the form was on, as a path of this site. */
|
||||
private function pageOf(Request $request): ?string
|
||||
{
|
||||
$path = parse_url((string) $request->headers->get('referer'), PHP_URL_PATH);
|
||||
|
||||
return is_string($path) && $path !== '' ? mb_substr($path, 0, 300) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Leads;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadBlock;
|
||||
use IriksIT\Manager\Support\Leads\Intake;
|
||||
use IriksIT\Manager\Support\Leads\Phone;
|
||||
use IriksIT\Manager\Support\Leads\Report;
|
||||
|
||||
/**
|
||||
* The requests. Whoever may see them sees what is waiting and what was handled, and calls, apps or mails back. Whoever may manage
|
||||
* them also sees what the screening kept away ("other" and spam), with the reasons, and can move requests or block senders.
|
||||
*/
|
||||
class LeadsController
|
||||
{
|
||||
private const VIEWS = ['waiting', 'handled'];
|
||||
|
||||
public function index(Request $request, Report $report): JsonResponse
|
||||
{
|
||||
$manages = Gate::allows('leads.manage');
|
||||
$view = $request->string('view')->toString();
|
||||
$view = in_array($view, $manages ? [...self::VIEWS, Lead::OTHER, Lead::SPAM] : self::VIEWS, true) ? $view : 'waiting';
|
||||
|
||||
$query = Lead::query()->latest('id');
|
||||
match ($view) {
|
||||
'waiting' => $query->waiting(),
|
||||
'handled' => $query->handled(),
|
||||
default => $query->where('folder', $view),
|
||||
};
|
||||
|
||||
return response()->json([
|
||||
'view' => $view,
|
||||
'items' => $query->limit(200)->get()->map(fn (Lead $lead) => $this->present($lead, $manages))->values(),
|
||||
'counts' => [
|
||||
'waiting' => Lead::query()->waiting()->count(),
|
||||
'handled' => Lead::query()->handled()->count(),
|
||||
// How much was kept away; the folders themselves are only for who manages.
|
||||
'other' => Lead::query()->where('folder', Lead::OTHER)->count(),
|
||||
'spam' => Lead::query()->where('folder', Lead::SPAM)->count(),
|
||||
],
|
||||
'open' => $request->integer('open') ?: null,
|
||||
'blocks' => $manages ? LeadBlock::query()->latest('id')->get()->map(fn (LeadBlock $block) => [
|
||||
'id' => $block->id, 'type' => $block->type, 'value' => $block->value, 'reason' => $block->reason, 'expires_at' => $block->expires_at?->toIso8601String(),
|
||||
])->values() : null,
|
||||
// What the forms and the contact buttons brought in, the last 90 days.
|
||||
'report' => $manages ? $report->over(90) : null,
|
||||
'can' => ['handle' => Gate::allows('leads.handle'), 'manage' => $manages, 'delete' => Gate::allows('leads.delete')],
|
||||
]);
|
||||
}
|
||||
|
||||
/** The first time a request is opened: it is no longer new. */
|
||||
public function opened(int $lead): JsonResponse
|
||||
{
|
||||
$lead = Lead::findOrFail($lead);
|
||||
$lead->opened_at ??= now();
|
||||
$lead->save();
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
/** "Handled", and back; with whether it became a job, when that is said. */
|
||||
public function handled(Request $request, int $lead): JsonResponse
|
||||
{
|
||||
$lead = Lead::findOrFail($lead);
|
||||
$request->validate(['handled' => ['required', 'boolean'], 'outcome' => ['nullable', Rule::in([Lead::WON, Lead::LOST])]]);
|
||||
|
||||
$handled = $request->boolean('handled');
|
||||
|
||||
$lead->update([
|
||||
'handled_at' => $handled ? ($lead->handled_at ?? now()) : null,
|
||||
'outcome' => $handled && $request->filled('outcome') ? $request->string('outcome')->toString() : ($handled ? $lead->outcome : null),
|
||||
'opened_at' => $lead->opened_at ?? now(),
|
||||
]);
|
||||
|
||||
return response()->json($this->present($lead->refresh(), Gate::allows('leads.manage')));
|
||||
}
|
||||
|
||||
/** A note of the owner to themselves. */
|
||||
public function note(Request $request, int $lead): JsonResponse
|
||||
{
|
||||
$lead = Lead::findOrFail($lead);
|
||||
$request->validate(['text' => ['required', 'string', 'max:2000']]);
|
||||
|
||||
$lead->update(['notes' => [
|
||||
...($lead->notes ?? []),
|
||||
['at' => now()->format('Y-m-d H:i:s'), 'by' => Auth::user()?->name, 'text' => $request->string('text')->trim()->toString()],
|
||||
]]);
|
||||
|
||||
return response()->json($this->present($lead->refresh(), Gate::allows('leads.manage')), 201);
|
||||
}
|
||||
|
||||
/** Moves a request to another folder: the screening made the wrong call, or let something through. */
|
||||
public function folder(Request $request, Intake $intake, int $lead): JsonResponse
|
||||
{
|
||||
$lead = Lead::findOrFail($lead);
|
||||
$request->validate(['folder' => ['required', Rule::in(Lead::FOLDERS)]]);
|
||||
|
||||
$folder = $request->string('folder')->toString();
|
||||
$was = $lead->folder;
|
||||
|
||||
$lead->update(['folder' => $folder, 'reasons' => [...($lead->reasons ?? []), 'Moved by hand from '.$was.' to '.$folder]]);
|
||||
|
||||
// A real request after all: the owner hears about it like about any new one.
|
||||
if ($folder === Lead::INBOX && $was !== Lead::INBOX && $lead->notified_at === null) {
|
||||
$intake->tellTheOwner($lead);
|
||||
}
|
||||
|
||||
return response()->json($this->present($lead->refresh(), true));
|
||||
}
|
||||
|
||||
/** Keeps a sender out: what they send from now on goes to the spam folder. */
|
||||
public function block(Request $request, int $lead): JsonResponse
|
||||
{
|
||||
$lead = Lead::findOrFail($lead);
|
||||
$request->validate([
|
||||
'type' => ['required', Rule::in(LeadBlock::TYPES)],
|
||||
'days' => ['nullable', 'integer', 'min:1', 'max:3650'],
|
||||
'reason' => ['nullable', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$type = $request->string('type')->toString();
|
||||
$email = mb_strtolower((string) $lead->email);
|
||||
|
||||
$value = match ($type) {
|
||||
LeadBlock::EMAIL => $email,
|
||||
LeadBlock::DOMAIN => substr((string) strrchr($email, '@'), 1),
|
||||
LeadBlock::PHONE => (string) Phone::international((string) $lead->phone),
|
||||
default => (string) $lead->ip,
|
||||
};
|
||||
|
||||
if ($value === '') {
|
||||
return response()->json(['message' => __('This request has nothing of that kind to block.')], 422);
|
||||
}
|
||||
|
||||
// Half the country mails from these: blocking one would keep customers out.
|
||||
if ($type === LeadBlock::DOMAIN && in_array($value, LeadBlock::SHARED_DOMAINS, true)) {
|
||||
return response()->json(['message' => __('Everyone uses :domain: block the mail address instead of the whole domain.', ['domain' => $value])], 422);
|
||||
}
|
||||
|
||||
$block = LeadBlock::query()->updateOrCreate(['type' => $type, 'value' => $value], [
|
||||
'reason' => $request->filled('reason') ? $request->string('reason')->toString() : null,
|
||||
'expires_at' => $request->filled('days') ? now()->addDays($request->integer('days')) : null,
|
||||
'user_id' => Auth::id(),
|
||||
'user_name' => Auth::user()?->name,
|
||||
]);
|
||||
|
||||
return response()->json(['id' => $block->id, 'type' => $type, 'value' => $value], 201);
|
||||
}
|
||||
|
||||
public function unblock(int $block): JsonResponse
|
||||
{
|
||||
LeadBlock::findOrFail($block)->delete();
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
public function destroy(int $lead): JsonResponse
|
||||
{
|
||||
Lead::findOrFail($lead)->delete();
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A request as the screen shows it. The reasons of the screening, the address it came from and where the visit came from are
|
||||
* only for whoever manages the requests.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function present(Lead $lead, bool $manages): array
|
||||
{
|
||||
$digits = $lead->phone ? Phone::international($lead->phone) : null;
|
||||
|
||||
return [
|
||||
'id' => $lead->id,
|
||||
'kind' => $lead->kindLabel(),
|
||||
'subject' => $lead->aboutLine(),
|
||||
'name' => $lead->name,
|
||||
'phone' => $lead->phone,
|
||||
'email' => $lead->email,
|
||||
'prefers' => $lead->prefers,
|
||||
'message' => $lead->message,
|
||||
'answers' => $lead->answers ?? [],
|
||||
'location' => $lead->location,
|
||||
'page' => $lead->page,
|
||||
'call_link' => $digits ? 'tel:+'.$digits : null,
|
||||
'whatsapp_link' => $digits ? 'https://wa.me/'.$digits : null,
|
||||
'mail_link' => $lead->email ? 'mailto:'.$lead->email : null,
|
||||
'is_new' => $lead->opened_at === null,
|
||||
'handled' => $lead->handled_at !== null,
|
||||
'outcome' => $lead->outcome,
|
||||
'notes' => $lead->notes ?? [],
|
||||
'created_at' => $lead->created_at?->toIso8601String(),
|
||||
'notify_failed' => $lead->notify_failed,
|
||||
...($manages ? [
|
||||
'folder' => $lead->folder,
|
||||
'reasons' => $lead->reasons ?? [],
|
||||
'source' => trim(($lead->channel ?? '').($lead->source ? ': '.$lead->source : '')) ?: null,
|
||||
'ip' => $lead->ip,
|
||||
] : []),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Leads;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use IriksIT\Manager\Console\LeadsPruneCommand;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* The requests of visitors (callback requests, questions, quotes, a contact form): stored, screened into folders, handled and kept for
|
||||
* a while. The forms are the site's own and call `Support\Leads\Intake`. With a feature `leads` in `manager.features`, one switch
|
||||
* turns the module on and off.
|
||||
*/
|
||||
class LeadsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'leads';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Requests';
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['leads', 'lead_blocks', 'lead_taps'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('leads.view', 'See the requests that came in', 'Requests'),
|
||||
new Permission('leads.handle', 'Handle requests: mark as handled, add notes', 'Requests', needs: ['leads.view']),
|
||||
new Permission('leads.manage', 'See what the screening kept away, move requests and block senders', 'Requests', needs: ['leads.handle']),
|
||||
new Permission('leads.delete', 'Delete requests', 'Requests', needs: ['leads.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Requests', 'section' => 'Visitors', 'route' => Names::route('leads.index'), 'permission' => 'leads.view', 'simple' => true, 'hint' => 'The messages and requests from your website']];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> what the settings screen can change */
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'manager.leads.notify' => ['label' => 'Mail new requests to', 'type' => 'text', 'group' => 'Requests', 'sensitive' => true, 'help' => 'The mail address that is told about every real request', 'env' => 'MANAGER_LEADS_NOTIFY'],
|
||||
'manager.leads.confirm' => ['label' => 'Mail the visitor a confirmation', 'type' => 'toggle', 'group' => 'Requests'],
|
||||
'manager.leads.keep_days' => ['label' => 'Days a request is kept', 'type' => 'number', 'group' => 'Requests'],
|
||||
'manager.leads.keep_spam_days' => ['label' => 'Days spam is kept', 'type' => 'number', 'group' => 'Requests'],
|
||||
];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
// A form may be sent so many times an hour per address, and by everyone together. Over the limit the visitor is told to wait.
|
||||
RateLimiter::for('manager-leads', fn (Request $request) => [
|
||||
Limit::perHour(max(1, (int) config('manager.leads.form.per_hour', 6)))->by('lead|'.$request->ip()),
|
||||
Limit::perHour(max(1, (int) config('manager.leads.form.per_hour_all', 120)))->by('lead-all'),
|
||||
]);
|
||||
RateLimiter::for('manager-leads-token', fn (Request $request) => Limit::perMinute(60)->by((string) $request->ip()));
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [LeadsPruneCommand::class];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'leads.handled' => ['Marked a request as handled or open'],
|
||||
'leads.note' => ['Added a note to a request'],
|
||||
'leads.folder' => ['Moved a request to another folder'],
|
||||
'leads.block' => ['Blocked a sender'],
|
||||
'leads.unblock' => ['Lifted the block of a sender'],
|
||||
'leads.destroy' => ['Deleted a request'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['leads.index' => 'Opened the requests', 'leads.opened' => 'Opened a request'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// A request of a visitor: a callback request, a question or a quote request (the kinds are the site's to name).
|
||||
Tables::create(Names::table('leads'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('kind', 20)->index();
|
||||
// inbox (a real request), other (acquisition, something else) or spam. Set by the screening.
|
||||
$table->string('folder', 20)->default('inbox')->index();
|
||||
// Why it is in that folder, for who looks after the screening.
|
||||
$table->json('reasons')->nullable();
|
||||
$table->string('name');
|
||||
$table->string('phone', 40)->nullable();
|
||||
$table->string('email')->nullable();
|
||||
// How the visitor wants to be reached: phone, whatsapp or email.
|
||||
$table->string('prefers', 20)->nullable();
|
||||
// What the visitor ticked: a job, or something else.
|
||||
$table->string('about', 20)->default('job');
|
||||
$table->text('message')->nullable();
|
||||
// To see that the same text was sent before.
|
||||
$table->string('message_hash', 64)->nullable()->index();
|
||||
// What was tapped in the steps of a form, and when a callback suits.
|
||||
$table->json('answers')->nullable();
|
||||
$table->string('location', 120)->nullable();
|
||||
// What the request is about, as the site names it (a service, a product): a label and the id it points to.
|
||||
$table->string('subject', 255)->nullable();
|
||||
$table->unsignedBigInteger('subject_id')->nullable();
|
||||
// The page the form was on, and where the visit came from.
|
||||
$table->string('page', 300)->nullable();
|
||||
$table->string('channel', 20)->nullable();
|
||||
$table->string('source', 80)->nullable();
|
||||
// The address it was sent from, to be able to block a sender. Goes with the request.
|
||||
$table->string('ip', 45)->nullable();
|
||||
$table->dateTime('opened_at')->nullable();
|
||||
$table->dateTime('handled_at')->nullable();
|
||||
// won or lost, when that was said.
|
||||
$table->string('outcome', 20)->nullable();
|
||||
// Notes of the owner: a list of {at, by, text}.
|
||||
$table->json('notes')->nullable();
|
||||
$table->dateTime('notified_at')->nullable();
|
||||
$table->boolean('notify_failed')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
// A sender that is kept out: what they send goes to the spam folder.
|
||||
Tables::create(Names::table('lead_blocks'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
// email, domain, phone or ip.
|
||||
$table->string('type', 20);
|
||||
$table->string('value');
|
||||
$table->string('reason')->nullable();
|
||||
$table->dateTime('expires_at')->nullable();
|
||||
$table->unsignedBigInteger('user_id')->nullable();
|
||||
$table->string('user_name')->nullable();
|
||||
$table->timestamps();
|
||||
$table->unique(['type', 'value']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('lead_blocks'));
|
||||
Schema::dropIfExists(Names::table('leads'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::create(Names::table('lead_taps'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('day', 10);
|
||||
// call or whatsapp.
|
||||
$table->string('kind', 20);
|
||||
$table->string('path', 255);
|
||||
$table->unsignedInteger('taps')->default(0);
|
||||
$table->unique(['day', 'kind', 'path']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('lead_taps'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/**
|
||||
* For a site that already has a table of requests (`manager.tables`): adds what the package wants to know about what a
|
||||
* request is about. A table that has `service_id` (the old way: one kind of work) gives that id to `subject_id`; the old
|
||||
* column stays, the site drops it when its own code no longer reads it. On a table the package made itself this does nothing.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$table = Names::table('leads');
|
||||
|
||||
if (! Schema::hasTable($table)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$hadSubjectId = Schema::hasColumn($table, 'subject_id');
|
||||
|
||||
Tables::addColumn($table, 'subject', fn (Blueprint $blueprint) => $blueprint->string('subject', 255)->nullable());
|
||||
Tables::addColumn($table, 'subject_id', fn (Blueprint $blueprint) => $blueprint->unsignedBigInteger('subject_id')->nullable());
|
||||
|
||||
if (! $hadSubjectId && Schema::hasColumn($table, 'service_id')) {
|
||||
DB::table($table)->whereNotNull('service_id')->update(['subject_id' => DB::raw('service_id')]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// The columns may have been there before the package: nothing to take away.
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Leads\LeadFormController;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
// The forms of the public site. No session needed, nothing of the manager: `POST /{path}/{form}` takes a request in, `GET /{path}/token` gives a
|
||||
// signed moment for a form that is built by script (a form in a page can use `Intake::formToken()`).
|
||||
$path = trim((string) config('manager.leads.form.path', 'requests'), '/');
|
||||
|
||||
Route::get($path.'/token', [LeadFormController::class, 'token'])->middleware('throttle:manager-leads-token')->name(Names::route('leads.token'));
|
||||
Route::post($path.'/tap', [LeadFormController::class, 'tap'])->middleware('throttle:manager-leads-token')->name(Names::route('leads.tap'));
|
||||
Route::post($path.'/{form}', [LeadFormController::class, 'store'])->where('form', '[a-z0-9_-]+')->middleware(['web', 'throttle:manager-leads'])->name(Names::route('leads.store'));
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Leads\LeadsController;
|
||||
|
||||
Route::prefix('/leads')->where(['lead' => '[0-9]+', 'block' => '[0-9]+'])->group(function () {
|
||||
Route::get('/', [LeadsController::class, 'index'])->name('leads.index')->middleware('can:leads.view');
|
||||
Route::post('/{lead}/opened', [LeadsController::class, 'opened'])->name('leads.opened')->middleware('can:leads.view');
|
||||
Route::put('/{lead}/handled', [LeadsController::class, 'handled'])->name('leads.handled')->middleware('can:leads.handle');
|
||||
Route::post('/{lead}/notes', [LeadsController::class, 'note'])->name('leads.note')->middleware('can:leads.handle');
|
||||
Route::put('/{lead}/folder', [LeadsController::class, 'folder'])->name('leads.folder')->middleware('can:leads.manage');
|
||||
Route::post('/{lead}/block', [LeadsController::class, 'block'])->name('leads.block')->middleware('can:leads.manage');
|
||||
Route::delete('/blocks/{block}', [LeadsController::class, 'unblock'])->name('leads.unblock')->middleware('can:leads.manage');
|
||||
Route::delete('/{lead}', [LeadsController::class, 'destroy'])->name('leads.destroy')->middleware('can:leads.delete');
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
|
||||
/**
|
||||
* The media library. The library (also when opened as a picker from another form) loads and
|
||||
* changes its items through these JSON actions.
|
||||
*/
|
||||
class MediaController
|
||||
{
|
||||
private const UNAVAILABLE = 'The file storage is not available right now. Try again in a moment.';
|
||||
|
||||
public function __construct(private readonly MediaLibrary $library) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json($this->limits());
|
||||
}
|
||||
|
||||
public function items(): JsonResponse
|
||||
{
|
||||
$media = Media::query()->with('uploader')->latest()->latest('id')->get();
|
||||
$usage = $this->library->usageCounts($media);
|
||||
|
||||
return response()->json([
|
||||
'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(),
|
||||
...$this->limits(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)],
|
||||
...$this->focusRules(),
|
||||
]);
|
||||
|
||||
$file = $request->file('file');
|
||||
abort_unless($file instanceof UploadedFile, 422);
|
||||
|
||||
$room = $this->library->room();
|
||||
|
||||
if ($file->getSize() > $room['left']) {
|
||||
$message = __('The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.');
|
||||
|
||||
return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$media = $this->library->store($file, $request->user());
|
||||
} catch (MediaStorageException $e) {
|
||||
return $this->unavailable($e);
|
||||
}
|
||||
|
||||
if ($media->isImage()) {
|
||||
$media->update($this->focus($request));
|
||||
}
|
||||
|
||||
return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $media): JsonResponse
|
||||
{
|
||||
$media = Media::query()->findOrFail($media);
|
||||
app(AuditTrail::class)->about($media);
|
||||
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:250'],
|
||||
'alt' => ['nullable', 'string', 'max:500'],
|
||||
...$this->focusRules(),
|
||||
]);
|
||||
|
||||
$alt = $request->string('alt')->trim()->toString();
|
||||
|
||||
$media->update([
|
||||
'name' => $request->string('name')->trim()->toString(),
|
||||
'alt' => $alt !== '' ? $alt : null,
|
||||
// Only when the request says something about it; renaming keeps the focus point.
|
||||
...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []),
|
||||
]);
|
||||
|
||||
$usage = $this->library->usageCounts([$media]);
|
||||
|
||||
return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]);
|
||||
}
|
||||
|
||||
public function destroy(string $media): JsonResponse
|
||||
{
|
||||
$media = Media::query()->findOrFail($media);
|
||||
app(AuditTrail::class)->about($media);
|
||||
|
||||
try {
|
||||
$this->library->delete($media);
|
||||
} catch (MediaStorageException $e) {
|
||||
return $this->unavailable($e);
|
||||
}
|
||||
|
||||
return response()->json(['deleted' => true, 'storage' => $this->library->room()]);
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
private function focusRules(): array
|
||||
{
|
||||
return [
|
||||
'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'],
|
||||
'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */
|
||||
private function focus(Request $request): array
|
||||
{
|
||||
$x = $request->input('focus_x');
|
||||
$y = $request->input('focus_y');
|
||||
$set = is_numeric($x) && is_numeric($y);
|
||||
|
||||
return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null];
|
||||
}
|
||||
|
||||
/** The reason goes to the log; the browser only hears that it did not work. */
|
||||
private function unavailable(MediaStorageException $e): JsonResponse
|
||||
{
|
||||
Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]);
|
||||
|
||||
return response()->json(['message' => __(self::UNAVAILABLE)], 502);
|
||||
}
|
||||
|
||||
/** @return array{max_file_mb: int, extensions: list<string>, storage: array{used: int, limit: int, left: int}} */
|
||||
private function limits(): array
|
||||
{
|
||||
return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()];
|
||||
}
|
||||
|
||||
private function maxMegabytes(): int
|
||||
{
|
||||
return max(1, config()->integer('manager.media.max_file_mb'));
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function extensions(): array
|
||||
{
|
||||
return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** Passes a media file on to the browser, with ETag and byte ranges (video needs them). */
|
||||
class MediaFileController
|
||||
{
|
||||
/**
|
||||
* Types a browser may show as they are. Anything else is offered as a download, so a
|
||||
* stored file can never run as a page on this domain.
|
||||
*/
|
||||
private const array INLINE_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/webp', 'image/gif',
|
||||
'video/mp4', 'video/webm',
|
||||
'application/pdf',
|
||||
];
|
||||
|
||||
public function __invoke(Request $request, MediaLibrary $library, string $media): Response
|
||||
{
|
||||
$media = Media::query()->findOrFail((int) $media);
|
||||
|
||||
$headers = $this->headers($media);
|
||||
|
||||
// A media id never gets other content, so what the browser has is still right.
|
||||
if (in_array($headers['ETag'], $request->getETags(), true)) {
|
||||
return response('', 304, $headers);
|
||||
}
|
||||
|
||||
$range = $this->range($request, $media->size);
|
||||
|
||||
if ($range === null) {
|
||||
return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers);
|
||||
}
|
||||
|
||||
[$start, $end, $partial] = $range;
|
||||
$length = $end - $start + 1;
|
||||
|
||||
$headers['Content-Length'] = (string) $length;
|
||||
|
||||
if ($partial) {
|
||||
$headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}";
|
||||
}
|
||||
|
||||
if ($request->isMethod('HEAD')) {
|
||||
return response('', $partial ? 206 : 200, $headers);
|
||||
}
|
||||
|
||||
try {
|
||||
$stream = $library->open($media);
|
||||
} catch (MediaStorageException $e) {
|
||||
if ($e->status === 404) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']);
|
||||
}
|
||||
|
||||
return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function headers(Media $media): array
|
||||
{
|
||||
$inline = in_array($media->mime_type, self::INLINE_TYPES, true);
|
||||
$name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename);
|
||||
|
||||
return [
|
||||
'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream',
|
||||
'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Accept-Ranges' => 'bytes',
|
||||
'Cache-Control' => 'public, max-age=31536000, immutable',
|
||||
'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of the file the browser asks for: [first byte, last byte, is it a part].
|
||||
* Null when the request asks for bytes the file does not have.
|
||||
*
|
||||
* @return array{int, int, bool}|null
|
||||
*/
|
||||
private function range(Request $request, int $size): ?array
|
||||
{
|
||||
$header = $request->headers->get('Range');
|
||||
$whole = [0, max($size - 1, 0), false];
|
||||
|
||||
// No range, an empty file, or something other than one plain byte range: send it all.
|
||||
if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) {
|
||||
return $whole;
|
||||
}
|
||||
|
||||
[, $first, $last] = $match;
|
||||
|
||||
if ($first === '' && $last === '') {
|
||||
return $whole;
|
||||
}
|
||||
|
||||
if ($first === '') {
|
||||
// "bytes=-500": the last 500 bytes.
|
||||
$start = max($size - (int) $last, 0);
|
||||
$end = $size - 1;
|
||||
} else {
|
||||
$start = (int) $first;
|
||||
$end = $last === '' ? $size - 1 : min((int) $last, $size - 1);
|
||||
}
|
||||
|
||||
if ($start >= $size || $start > $end) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [$start, $end, true];
|
||||
}
|
||||
|
||||
/** @param resource $stream */
|
||||
private function send($stream, int $start, int $length): void
|
||||
{
|
||||
try {
|
||||
if ($start > 0 && stream_get_meta_data($stream)['seekable']) {
|
||||
fseek($stream, $start);
|
||||
} else {
|
||||
$skip = $start;
|
||||
|
||||
while ($skip > 0 && ! feof($stream)) {
|
||||
$chunk = fread($stream, min(65536, $skip));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
$skip -= strlen($chunk);
|
||||
}
|
||||
}
|
||||
|
||||
while ($length > 0 && ! feof($stream)) {
|
||||
$chunk = fread($stream, min(65536, $length));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
echo $chunk;
|
||||
flush();
|
||||
|
||||
$length -= strlen($chunk);
|
||||
}
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
|
||||
/**
|
||||
* The one place that knows where media files physically are. Everything else works with Media
|
||||
* rows and their URLs. New uploads go to the disk in config('manager.media.disk'); an existing
|
||||
* file is always read from and deleted on the disk its own row names.
|
||||
*/
|
||||
class MediaLibrary
|
||||
{
|
||||
public function __construct(private readonly MediaUsage $usage) {}
|
||||
|
||||
/** @throws MediaStorageException */
|
||||
public function store(UploadedFile $file, ?Authenticatable $uploader = null, ?string $disk = null): Media
|
||||
{
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
$baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
|
||||
$filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : '');
|
||||
$path = $file->getRealPath();
|
||||
|
||||
if ($path === false) {
|
||||
throw new MediaStorageException('The uploaded file could not be read.');
|
||||
}
|
||||
|
||||
$mimeType = $file->getMimeType() ?? 'application/octet-stream';
|
||||
$dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false;
|
||||
$disk ??= config('manager.media.disk');
|
||||
|
||||
$location = $file->store('media/'.now()->format('Y/m'), $disk);
|
||||
|
||||
if ($location === false) {
|
||||
throw new MediaStorageException('The file could not be stored.');
|
||||
}
|
||||
|
||||
return Media::create([
|
||||
'disk' => $disk,
|
||||
'location' => $location,
|
||||
'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''),
|
||||
'filename' => $filename,
|
||||
'mime_type' => $mimeType,
|
||||
'size' => (int) $file->getSize(),
|
||||
'checksum' => hash_file('sha256', $path) ?: null,
|
||||
'width' => $dimensions !== false ? $dimensions[0] : null,
|
||||
'height' => $dimensions !== false ? $dimensions[1] : null,
|
||||
'uploaded_by' => $uploader?->getAuthIdentifier(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a file to another disk: copy it (the same location on the new disk), check the size (and, with $verify, what comes
|
||||
* back), only then point the row at the new disk and, when asked, delete the original. The address of the file does not
|
||||
* change, because it holds the id of the row. A file that is already there is not copied again.
|
||||
*
|
||||
* @throws MediaStorageException with the file still where it was
|
||||
*/
|
||||
public function move(Media $media, string $disk, bool $deleteSource = false, bool $verify = false): void
|
||||
{
|
||||
$from = Storage::disk($media->disk);
|
||||
$to = Storage::disk($disk);
|
||||
|
||||
$wrote = false;
|
||||
|
||||
if (! $to->exists($media->location)) {
|
||||
$stream = $this->open($media);
|
||||
|
||||
try {
|
||||
$stored = $to->put($media->location, $stream);
|
||||
} finally {
|
||||
is_resource($stream) && fclose($stream);
|
||||
}
|
||||
|
||||
if ($stored === false) {
|
||||
throw new MediaStorageException('The file could not be written to the new disk.');
|
||||
}
|
||||
|
||||
$wrote = true;
|
||||
}
|
||||
|
||||
if ($to->size($media->location) !== (int) $media->size) {
|
||||
$wrote && $to->delete($media->location);
|
||||
|
||||
throw new MediaStorageException('The copy on the new disk is not the size of the original.');
|
||||
}
|
||||
|
||||
if ($verify && $media->checksum !== null && hash('sha256', (string) $to->get($media->location)) !== $media->checksum) {
|
||||
$wrote && $to->delete($media->location);
|
||||
|
||||
throw new MediaStorageException('The copy on the new disk is not the same as the original.');
|
||||
}
|
||||
|
||||
$source = $media->disk;
|
||||
$media->update(['disk' => $disk]);
|
||||
|
||||
if ($deleteSource && $source !== $disk) {
|
||||
Storage::disk($source)->delete($media->location);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How full the library is: what all files together take, how much it may hold
|
||||
* (`manager.media.max_total_gb`) and what is left. In bytes.
|
||||
*
|
||||
* @return array{used: int, limit: int, left: int}
|
||||
*/
|
||||
public function room(): array
|
||||
{
|
||||
$configured = config('manager.media.max_total_gb');
|
||||
$limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000);
|
||||
$used = (int) Media::query()->sum('size');
|
||||
|
||||
return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a file's content as a stream. Read it and close it.
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @throws MediaStorageException with status 404 when the file is gone
|
||||
*/
|
||||
public function open(Media $media)
|
||||
{
|
||||
$stream = Storage::disk($media->disk)->readStream($media->location);
|
||||
|
||||
if (! is_resource($stream)) {
|
||||
throw new MediaStorageException('The file is no longer there.', 404);
|
||||
}
|
||||
|
||||
return $stream;
|
||||
}
|
||||
|
||||
/** Delete the file and then its row. When the storage refuses, the row stays. */
|
||||
public function delete(Media $media): void
|
||||
{
|
||||
$disk = Storage::disk($media->disk);
|
||||
|
||||
if ($disk->exists($media->location) && ! $disk->delete($media->location)) {
|
||||
throw new MediaStorageException('The file could not be deleted.');
|
||||
}
|
||||
|
||||
$media->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* How often each media file is used, keyed by media id: how many of the registered sources
|
||||
* (MediaUsage) hold its address. Nothing registered means 0.
|
||||
*
|
||||
* @param iterable<Media> $items
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function usageCounts(iterable $items): array
|
||||
{
|
||||
$haystacks = $this->usage->haystacks();
|
||||
$counts = [];
|
||||
|
||||
foreach ($items as $media) {
|
||||
$prefix = $media->urlPrefix();
|
||||
$counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix)));
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Media;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class MediaModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'media';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Media';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['media', 'storage_files'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('media.view', 'See the media library and pick files from it', 'Media'),
|
||||
new Permission('media.upload', 'Upload files', 'Media', needs: ['media.view']),
|
||||
new Permission('media.edit', 'Change the name, description and focus point of a file', 'Media', needs: ['media.view']),
|
||||
new Permission('media.delete', 'Delete files', 'Media', needs: ['media.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Media', 'section' => 'Content', 'route' => Names::route('media.index'), 'permission' => 'media.view', 'simple' => true, 'hint' => 'Your photos and files'],
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'media.store' => ['Uploaded a file'],
|
||||
'media.update' => ['Changed a file'],
|
||||
'media.destroy' => ['Deleted a file'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['media.index' => 'Opened the media library', 'media.items' => ''];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$users = (new (config('manager.user_model')))->getTable();
|
||||
|
||||
// The file itself is elsewhere: `disk` says where, `location` is its path there.
|
||||
Tables::create(Names::table('media'), function (Blueprint $table) use ($users) {
|
||||
$table->id();
|
||||
$table->string('disk', 40);
|
||||
$table->string('location');
|
||||
$table->string('name');
|
||||
$table->string('filename');
|
||||
$table->string('mime_type', 100);
|
||||
$table->unsignedBigInteger('size');
|
||||
$table->string('checksum', 64)->nullable();
|
||||
$table->unsignedInteger('width')->nullable();
|
||||
$table->unsignedInteger('height')->nullable();
|
||||
$table->string('alt', 500)->nullable();
|
||||
// The part of an image that must stay in view when it is cropped to fit:
|
||||
// 0-1 from the left and from the top.
|
||||
$table->decimal('focus_x', 5, 4)->nullable();
|
||||
$table->decimal('focus_y', 5, 4)->nullable();
|
||||
$table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('media'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// The IriksIT API knows a file by an id of its own: this remembers which id belongs to which path of the `iriksit` disk.
|
||||
Tables::create(Names::table('storage_files'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('path')->unique();
|
||||
$table->string('remote_id', 100);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('storage_files'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Media\MediaFileController;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
// Files of the media library, for visitors. No session and no cookies: this is a file, not a
|
||||
// page, and the browser may cache it for good. The address ends in /view on purpose: web servers
|
||||
// tend to answer anything that ends in .jpg themselves and never ask the app.
|
||||
Route::get('/media-files/{media}/{filename}/view', MediaFileController::class)
|
||||
->whereNumber('media')
|
||||
->middleware('throttle:media-files')
|
||||
->name(Names::route('media.file'));
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Media\MediaController;
|
||||
|
||||
Route::get('/media', [MediaController::class, 'index'])->name('media.index')->middleware('can:media.view');
|
||||
Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view');
|
||||
Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload');
|
||||
Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media');
|
||||
Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media');
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Numbers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Support\Numbers;
|
||||
|
||||
class NumbersController
|
||||
{
|
||||
public function index(Request $request, Numbers $numbers)
|
||||
{
|
||||
return response()->json($numbers->over((string) $request->query('range', Numbers::DEFAULT_PERIOD), Gate::forUser($request->user())->allows('leads.view')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Numbers;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/** How the site is doing, in plain words for the owner of the business. No tables: it reads the statistics and the requests. */
|
||||
class NumbersModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'numbers';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Numbers';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function requires(): array
|
||||
{
|
||||
return ['statistics'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [new Permission('numbers.view', 'See how the site is doing, in plain words', 'Site')];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Numbers', 'section' => 'Visitors', 'route' => Names::route('numbers.index'), 'permission' => 'numbers.view', 'simple' => true, 'hint' => 'How your website is doing', 'icon' => 'chart']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['numbers.index' => 'Opened the numbers'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Numbers\NumbersController;
|
||||
|
||||
Route::get('/numbers', [NumbersController::class, 'index'])->name('numbers.index')->middleware('can:numbers.view');
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\Blocks;
|
||||
use IriksIT\Manager\Support\Resources;
|
||||
|
||||
/** A page as JSON, for a frontend that is not Laravel's own (a Nuxt or Next site, an app): the fields, the blocks and the structured data. */
|
||||
class PageApiController
|
||||
{
|
||||
public function show(string $slug): JsonResponse
|
||||
{
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
|
||||
// A page with a definition always exists; a free page only once it is published.
|
||||
abort_if(($definition === null && ($page === null || ! $page->is_published)), 404);
|
||||
|
||||
$blocks = Blocks::for($slug);
|
||||
|
||||
return response()->json([
|
||||
'slug' => $slug,
|
||||
'title' => $page->title ?? $definition['title'],
|
||||
'meta_description' => $page->meta_description ?? null,
|
||||
'content' => $definition !== null ? Page::contentFor($slug) : null,
|
||||
'body' => $definition === null ? $page->body : null,
|
||||
'blocks' => $blocks,
|
||||
'structured_data' => Blocks::structuredData($blocks),
|
||||
])->header('Cache-Control', 'public, max-age=60');
|
||||
}
|
||||
|
||||
/** The block types: what a frontend has to know to draw them (fields, style choices). */
|
||||
public function schema(): JsonResponse
|
||||
{
|
||||
return response()->json(['types' => Blocks::catalogue(), 'tokens' => Blocks::tokens()])->header('Cache-Control', 'public, max-age=300');
|
||||
}
|
||||
|
||||
/**
|
||||
* The page of one record (a service, a project) as the blocks of the page layout of its list, with the record filled in. Only the blocks
|
||||
* go out, never the raw fields of the record (a list may hold fields that are not for the public); a record that is not active is not found.
|
||||
*/
|
||||
public function template(string $resource, string $id): JsonResponse
|
||||
{
|
||||
$definition = Resources::find($resource);
|
||||
abort_if($definition === null || $definition['template'] === false, 404);
|
||||
|
||||
$model = Resources::record($definition, $id);
|
||||
abort_if($model === null || ! (Resources::row($definition, $model)['values']['is_active'] ?? true), 404);
|
||||
|
||||
$blocks = Blocks::forRecord($resource, $model);
|
||||
|
||||
return response()->json([
|
||||
'resource' => $resource,
|
||||
'id' => $model->getKey(),
|
||||
'blocks' => $blocks,
|
||||
'structured_data' => Blocks::structuredData($blocks),
|
||||
])->header('Cache-Control', 'public, max-age=60');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\BlockPreview;
|
||||
use IriksIT\Manager\Support\Blocks;
|
||||
use IriksIT\Manager\Support\Fields;
|
||||
|
||||
/**
|
||||
* Pages: the ones a site defines (config `manager.pages.definitions`: a title and fields per slug) and free
|
||||
* pages with one text. A defined page needs no setup: it is made the first time it is saved.
|
||||
*/
|
||||
class PagesController
|
||||
{
|
||||
private const SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*';
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$definitions = Page::definitions();
|
||||
$stored = Page::query()->orderBy('title')->get()->keyBy('slug');
|
||||
$pages = [];
|
||||
|
||||
foreach ($definitions as $slug => $definition) {
|
||||
$pages[] = ['slug' => $slug, 'title' => $definition['title'], 'simple_title' => $definition['simple_title'], 'defined' => true, 'saved' => $stored->has($slug), 'updated_at' => $stored[$slug]->updated_at ?? null];
|
||||
}
|
||||
|
||||
foreach ($stored as $slug => $page) {
|
||||
if (! isset($definitions[$slug])) {
|
||||
$pages[] = ['slug' => $slug, 'title' => $page->title, 'defined' => false, 'saved' => true, 'is_published' => $page->is_published, 'updated_at' => $page->updated_at];
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json(['pages' => $pages]);
|
||||
}
|
||||
|
||||
public function show(string $slug): JsonResponse
|
||||
{
|
||||
return response()->json(['page' => $this->payload($slug)]);
|
||||
}
|
||||
|
||||
/** Makes a free page. A defined page is made by saving it. */
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'slug' => ['required', 'string', 'max:120', 'regex:/^'.self::SLUG.'$/', Rule::unique(Page::query()->getModel()->getTable(), 'slug'), Rule::notIn(array_keys(Page::definitions()))],
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$page = Page::query()->create($data + ['is_published' => false]);
|
||||
app(AuditTrail::class)->about($page);
|
||||
|
||||
return response()->json(['page' => $this->payload($page->slug)], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
abort_if($definition === null && $page === null, 404);
|
||||
|
||||
$rules = [
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'meta_description' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
|
||||
if ($definition !== null) {
|
||||
$rules = [...$rules, 'content' => ['nullable', 'array'], ...Fields::rules($definition['fields'], 'content.')];
|
||||
} else {
|
||||
$rules = [...$rules, 'body' => ['nullable', 'string', 'max:200000'], 'is_published' => ['boolean']];
|
||||
}
|
||||
|
||||
$allowedBlocks = Page::blockTypesFor($slug);
|
||||
|
||||
if ($allowedBlocks !== []) {
|
||||
$rules = [...$rules, ...Blocks::rules((array) $request->input('blocks', []), $allowedBlocks)];
|
||||
}
|
||||
|
||||
$data = $request->validate($rules);
|
||||
$values = ['title' => $data['title'], 'meta_description' => ($data['meta_description'] ?? '') ?: null];
|
||||
|
||||
if ($definition !== null) {
|
||||
$values['content'] = Fields::clean($definition['fields'], (array) ($data['content'] ?? []));
|
||||
} else {
|
||||
$values += ['body' => $data['body'] ?? null, 'is_published' => (bool) ($data['is_published'] ?? false)];
|
||||
}
|
||||
|
||||
if ($allowedBlocks !== [] && $request->has('blocks')) {
|
||||
$values['blocks'] = Blocks::clean((array) ($data['blocks'] ?? []), $allowedBlocks);
|
||||
|
||||
// Without `pages.layout` the texts of the blocks may change, the build of the page may not: the same blocks, in the same order.
|
||||
abort_unless(Gate::allows('pages.layout') || $this->sameBuild($page?->blocks, $values['blocks']), 403, __('You may change the texts of the blocks, but not add, move, hide or remove them.'));
|
||||
}
|
||||
|
||||
$page = $page ?? new Page(['slug' => $slug]);
|
||||
$page->fill($values)->save();
|
||||
app(AuditTrail::class)->about($page);
|
||||
|
||||
return response()->json(['page' => $this->payload($slug)]);
|
||||
}
|
||||
|
||||
/** Keeps the blocks the person sent and gives back the address of the public page that shows them (the live preview). */
|
||||
public function preview(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
abort_unless(BlockPreview::enabled(), 404);
|
||||
|
||||
$allowed = Page::blockTypesFor($slug);
|
||||
abort_if($allowed === [] || (Page::definitions()[$slug] ?? null) === null && ! Page::query()->where('slug', $slug)->exists(), 404);
|
||||
|
||||
$request->validate(['blocks' => ['present', 'array']]);
|
||||
|
||||
return response()->json(BlockPreview::store($slug, (array) $request->input('blocks'), $allowed));
|
||||
}
|
||||
|
||||
/** Removes a free page; a defined page stays (its values go back to the defaults when it is emptied by saving). */
|
||||
public function destroy(string $slug): JsonResponse
|
||||
{
|
||||
abort_if(isset(Page::definitions()[$slug]), 422, __('A page with fields of its own cannot be removed.'));
|
||||
|
||||
$page = Page::query()->where('slug', $slug)->firstOrFail();
|
||||
app(AuditTrail::class)->about($page);
|
||||
$page->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two lists are the same build: the same blocks (by id and type), hidden or not, in the same order.
|
||||
*
|
||||
* @param list<array<string, mixed>> $sent
|
||||
*/
|
||||
private function sameBuild(mixed $stored, array $sent): bool
|
||||
{
|
||||
$shape = fn (array $blocks) => array_map(fn ($block) => [$block['id'] ?? null, $block['type'] ?? null, (bool) ($block['hidden'] ?? false)], array_values($blocks));
|
||||
|
||||
return $shape(is_array($stored) ? $stored : []) === $shape($sent);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function payload(string $slug): array
|
||||
{
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
abort_if($definition === null && $page === null, 404);
|
||||
|
||||
$allowed = Page::blockTypesFor($slug);
|
||||
|
||||
return [
|
||||
'id' => $page?->id,
|
||||
'slug' => $slug,
|
||||
'title' => $page->title ?? $definition['title'],
|
||||
'simple_title' => $definition['simple_title'] ?? null,
|
||||
'meta_description' => $page->meta_description ?? '',
|
||||
'defined' => $definition !== null,
|
||||
'fields' => array_values($definition['fields'] ?? []),
|
||||
'content' => $definition !== null ? Fields::values($definition['fields'], is_array($page?->content) ? $page->content : []) : null,
|
||||
'body' => $definition === null ? (string) $page->body : null,
|
||||
'is_published' => $definition === null ? (bool) $page->is_published : null,
|
||||
// The blocks the page may hold: null when it holds none, so the screen shows nothing of them.
|
||||
'blocks' => $allowed === [] ? null : Blocks::forEditor(is_array($page?->blocks) ? $page->blocks : []),
|
||||
'block_types' => $allowed === [] ? null : Blocks::catalogue($allowed),
|
||||
'can_layout' => Gate::allows('pages.layout'),
|
||||
// The public address of the page (to look at it, and, with the live preview on, to show it in the editor).
|
||||
'view_url' => $allowed === [] || ! BlockPreview::enabled() ? null : BlockPreview::address($slug),
|
||||
'preview' => $allowed !== [] && BlockPreview::enabled(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Frontend;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class PagesModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'pages';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Pages';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['pages', 'block_templates'];
|
||||
}
|
||||
|
||||
/** The page API for a frontend of its own and the pages the package draws itself (`manager.frontend`): nothing unless the site switches it on. */
|
||||
public function publicRoutes(): ?string
|
||||
{
|
||||
return Frontend::api() || Frontend::renders() ? __DIR__.'/public-routes.php' : null;
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('pages.edit', 'Change the texts of the pages', 'Site content'),
|
||||
new Permission('pages.layout', 'Add, move, hide and remove the blocks of a page', 'Site content', needs: ['pages.edit']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Pages', 'section' => 'Content', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'],
|
||||
];
|
||||
}
|
||||
|
||||
/** The tour: how a page of blocks is built and where the photos come from. Only for a site that has pages of blocks. */
|
||||
public function tutorial(): array
|
||||
{
|
||||
$blocks = (bool) config('manager.blocks.free_pages') || array_filter(Page::definitions(), fn ($definition) => ! empty($definition['blocks'])) !== [];
|
||||
|
||||
if (! $blocks) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
['title' => 'Build a page from parts', 'text' => 'A page is made of parts: a big photo with a title, a text, photos, questions and answers. Open a page, press "Add something to the page", pick a part and fill it in. The arrows move a part up or down.', 'image' => 'pages', 'menu' => 'pages.index', 'permission' => 'pages.layout'],
|
||||
['title' => 'Photos from your phone', 'text' => 'Wherever you can choose a photo, you can also pick one from your phone or take a new one. It is made smaller by itself, so do not worry about the size. Tip: hold your phone sideways for a wide photo and keep what matters in the middle.', 'image' => 'photos', 'permission' => 'media.upload'],
|
||||
];
|
||||
}
|
||||
|
||||
/** Where the media library looks for the use of a file: the texts of the pages. */
|
||||
public function views(): array
|
||||
{
|
||||
return ['pages.index' => 'Opened the pages', 'pages.show' => 'Opened a page'];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'pages.store' => ['Created a page'],
|
||||
'pages.update' => ['Changed a page'],
|
||||
'pages.destroy' => ['Removed a page'],
|
||||
'pages.preview' => ['Prepared a preview of a page'],
|
||||
];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
app(MediaUsage::class)->register(fn () => Page::query()->get(['body', 'content'])->flatMap(fn (Page $row) => [$row->body, ...array_values(array_filter((array) $row->content, 'is_string'))]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\Blocks;
|
||||
|
||||
/**
|
||||
* The pages drawn by the package itself (`manager.frontend.mode` = package), for a site that has no frontend code of its own. It is the
|
||||
* fallback route: it answers only an address nothing else answered, and only for a page that has blocks and is there (a page with a
|
||||
* definition, or a free page that is published). Anything else is the usual 404.
|
||||
*/
|
||||
class PublicPageController
|
||||
{
|
||||
public function __invoke(Request $request): Response
|
||||
{
|
||||
$path = trim($request->path(), '/');
|
||||
$slug = $path === '' ? (string) config('manager.blocks.preview.home', 'home') : $path;
|
||||
|
||||
abort_unless(preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1, 404);
|
||||
|
||||
$definition = Page::definitions()[$slug] ?? null;
|
||||
$page = Page::query()->where('slug', $slug)->first();
|
||||
|
||||
abort_if($definition === null && ($page === null || ! $page->is_published), 404);
|
||||
|
||||
$blocks = Blocks::for($slug);
|
||||
abort_if($blocks === [], 404);
|
||||
|
||||
return response()->view((string) config('manager.frontend.layout', 'manager::public.layout'), [
|
||||
'title' => $page->title ?? $definition['title'] ?? $slug,
|
||||
'description' => $page->meta_description ?? null,
|
||||
'blocks' => $blocks,
|
||||
'slug' => $slug,
|
||||
'css' => (string) file_get_contents(__DIR__.'/../../../resources/blocks/blocks.css'),
|
||||
])->header('Cache-Control', 'private, no-cache');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::create(Names::table('pages'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('slug')->unique();
|
||||
$table->string('title');
|
||||
$table->longText('body')->nullable();
|
||||
$table->boolean('is_published')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('pages'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/** The structured texts of a page (one value per defined field) and its description for search engines. */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$pages = Names::table('pages');
|
||||
|
||||
Tables::addColumn($pages, 'meta_description', fn (Blueprint $table) => $table->string('meta_description', 255)->nullable());
|
||||
Tables::addColumn($pages, 'content', fn (Blueprint $table) => $table->json('content')->nullable());
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('pages'), function (Blueprint $table) {
|
||||
$table->dropColumn(['meta_description', 'content']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/** The blocks of a page: an ordered list of `{id, type, data, style, hidden}` (see `Support\Blocks`). */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::addColumn(Names::table('pages'), 'blocks', fn (Blueprint $table) => $table->json('blocks')->nullable());
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// The column may have been there before the package: nothing to take away.
|
||||
}
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/** For a table of pages that the site already has (`manager.tables`) and that lacks the text or the published flag of a free page. */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$pages = Names::table('pages');
|
||||
|
||||
Tables::addColumn($pages, 'body', fn (Blueprint $table) => $table->longText('body')->nullable());
|
||||
Tables::addColumn($pages, 'is_published', fn (Blueprint $table) => $table->boolean('is_published')->default(false));
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// The columns may have been there before the package: nothing to take away.
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Tables;
|
||||
|
||||
/** The page layout of a list (`manager.resources.<key>.template`): the blocks of the page of one record, as a template (ADR-0013). */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::create(Names::table('block_templates'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('resource', 40)->unique();
|
||||
$table->json('blocks')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('block_templates'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Pages\PageApiController;
|
||||
use IriksIT\Manager\Modules\Pages\PublicPageController;
|
||||
use IriksIT\Manager\Support\Frontend;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
// The pages as JSON for a frontend of its own (`manager.blocks.api`, or the headless mode). Read only, nothing of the manager.
|
||||
if (Frontend::api()) {
|
||||
$path = trim((string) config('manager.blocks.api.path', 'api/manager'), '/');
|
||||
$middleware = array_values((array) config('manager.blocks.api.middleware', []));
|
||||
|
||||
Route::middleware($middleware)->prefix($path)->group(function () {
|
||||
Route::get('/pages/{slug}', [PageApiController::class, 'show'])->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*')->name(Names::route('blocks.page'));
|
||||
|
||||
Route::get('/templates/{resource}/{id}', [PageApiController::class, 'template'])->where(['resource' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+'])->name(Names::route('blocks.template'));
|
||||
|
||||
if (config('manager.blocks.api.schema', true)) {
|
||||
Route::get('/blocks/schema', [PageApiController::class, 'schema'])->name(Names::route('blocks.schema'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// The pages drawn by the package itself (`manager.frontend.mode` = package). A fallback: a route of the site always wins, and what is
|
||||
// not a page stays the 404 it was.
|
||||
if (Frontend::renders()) {
|
||||
Route::middleware(array_values((array) config('manager.frontend.middleware', ['web'])))->group(function () {
|
||||
Route::fallback(PublicPageController::class)->name(Names::route('public.page'));
|
||||
});
|
||||
}
|
||||
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user