This commit is contained in:
deploy-bot committed 2026-12-05 19:00:02 +00:00
commit 4769402b1b
298 files changed
+20934

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
<?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 {--retry : Ask again for rows the price source could not or would not 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
{
if ($this->option('retry')) {
$ledger->retry();
}
$items = $ledger->items(true);
$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.");
if ($open > 0) {
$this->line('Rows without a price are not asked again for an hour (or until --retry) when the price source could not answer, and never when it answered without one.');
}
return self::SUCCESS;
}
}
+233
View File
@@ -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').'.');
}
}
}
+84
View File
@@ -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;
}
}
+96
View File
@@ -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);
}
}
+38
View File
@@ -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;
}
}
+95
View File
@@ -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;
}
}
+97
View File
@@ -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;
}
}
+104
View File
@@ -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;
}
}
+144
View File
@@ -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 ?? '');
}
}
+66
View File
@@ -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;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use IriksIT\Manager\Support\TwoFactor\Authenticator;
/**
* Takes the second step away from an account that lost its phone and its recovery codes, for the one who cannot log in (the last super admin). The account
* sets it up again at its next login; its grace period is not given back.
*
* php artisan manager:two-factor-reset [email protected]
*/
class TwoFactorResetCommand extends Command
{
protected $signature = 'manager:two-factor-reset {email : The email address of the account}';
protected $description = 'Take the second step of login away from an account that lost its phone';
public function handle(Authenticator $authenticator): 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;
}
$authenticator->reset($user);
$authenticator->log('two_factor.reset', 'The second step was reset from the command line', null, $user);
$this->info('The second step of '.$user->email.' is off. It sets it up again at the next login.');
return self::SUCCESS;
}
}
+49
View File
@@ -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;
}
}
+57
View File
@@ -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;
}
}