v0.8.0
This commit is contained in:
commit
bf5c31169a
221 files changed
+16292
No files matched your search
@@ -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', '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', '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', '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', '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', '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,123 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
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']];
|
||||
}
|
||||
|
||||
$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)];
|
||||
}
|
||||
|
||||
$page = $page ?? new Page(['slug' => $slug]);
|
||||
$page->fill($values)->save();
|
||||
app(AuditTrail::class)->about($page);
|
||||
|
||||
return response()->json(['page' => $this->payload($slug)]);
|
||||
}
|
||||
|
||||
/** 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]);
|
||||
}
|
||||
|
||||
/** @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);
|
||||
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Pages;
|
||||
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
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'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('pages.edit', 'Change the texts of the pages', 'Site content'),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'],
|
||||
];
|
||||
}
|
||||
|
||||
/** 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'],
|
||||
];
|
||||
}
|
||||
|
||||
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,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,12 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Pages\PagesController;
|
||||
|
||||
Route::middleware('can:pages.edit')->group(function () {
|
||||
Route::get('/pages', [PagesController::class, 'index'])->name('pages.index');
|
||||
Route::post('/pages', [PagesController::class, 'store'])->name('pages.store');
|
||||
Route::get('/pages/{slug}', [PagesController::class, 'show'])->name('pages.show')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
Route::put('/pages/{slug}', [PagesController::class, 'update'])->name('pages.update')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
Route::delete('/pages/{slug}', [PagesController::class, 'destroy'])->name('pages.destroy')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*');
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Posts;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* The categories and tags of the posts: make one, rename one everywhere, merge two, or take one
|
||||
* off every post.
|
||||
*/
|
||||
class LabelController
|
||||
{
|
||||
public function __construct(private readonly PostLabels $labels) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json($this->labels->overview());
|
||||
}
|
||||
|
||||
/** A category or tag that no post uses yet; the post form offers it from then on. */
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$type = $this->type($request);
|
||||
$request->validate(['name' => $this->nameRules($type)], $this->messages());
|
||||
|
||||
$name = $request->string('name')->trim()->toString();
|
||||
|
||||
if (! $this->labels->create($type, $name)) {
|
||||
return response()->json(['message' => $already = __('The :type ":name" already exists.', ['type' => __($type), 'name' => $name]), 'errors' => ['name' => [$already]]], 422);
|
||||
}
|
||||
|
||||
return response()->json(['created' => $name], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$type = $this->type($request);
|
||||
$request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages());
|
||||
|
||||
$from = $request->string('name')->toString();
|
||||
$to = $request->string('new_name')->trim()->toString();
|
||||
|
||||
return response()->json(['posts' => $this->labels->rename($type, $from, $to)]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request): JsonResponse
|
||||
{
|
||||
$type = $this->type($request);
|
||||
$request->validate(['name' => ['required', 'string']]);
|
||||
|
||||
return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same limits as the post form.
|
||||
*
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private function nameRules(string $type): array
|
||||
{
|
||||
return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])];
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function messages(): array
|
||||
{
|
||||
$comma = 'A tag cannot hold a comma: the post form separates tags with it.';
|
||||
|
||||
return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma];
|
||||
}
|
||||
|
||||
private function type(Request $request): string
|
||||
{
|
||||
$request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]);
|
||||
|
||||
return $request->string('type')->toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Posts;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Markdown;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* The posts. A post that is live or scheduled is only changed or deleted by who may publish: a
|
||||
* change to it is on the site at once. Who may not publish only ever saves drafts.
|
||||
*
|
||||
* The answers have the shape the screens of the sites used as props.
|
||||
*/
|
||||
class PostController
|
||||
{
|
||||
public function __construct(private readonly PostLabels $labels) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$posts = Post::query()
|
||||
->orderByRaw('published_at is null desc')
|
||||
->latest('published_at')
|
||||
->latest('id')
|
||||
->get()
|
||||
->map(fn (Post $post) => [
|
||||
'id' => $post->id,
|
||||
'title' => $post->title,
|
||||
'slug' => $post->slug,
|
||||
'category' => $post->category,
|
||||
'is_featured' => $post->is_featured,
|
||||
'status' => $post->status(),
|
||||
'published_at' => $post->published_at?->toIso8601String(),
|
||||
'can_change' => Gate::allows('posts.write') && $this->mayTouch($post),
|
||||
'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post),
|
||||
])
|
||||
->values();
|
||||
|
||||
return response()->json(['posts' => $posts]);
|
||||
}
|
||||
|
||||
public function create(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'post' => null,
|
||||
'categories' => $this->labels->categories(),
|
||||
'known_tags' => $this->labels->names(PostLabels::TAG),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$post = Post::create($this->validated($request));
|
||||
|
||||
return response()->json(['id' => $post->id], 201);
|
||||
}
|
||||
|
||||
public function edit(string $post): JsonResponse
|
||||
{
|
||||
$post = Post::query()->findOrFail($post);
|
||||
abort_unless($this->mayTouch($post), 403);
|
||||
|
||||
return response()->json([
|
||||
'post' => [
|
||||
'id' => $post->id,
|
||||
'title' => $post->title,
|
||||
'slug' => $post->slug,
|
||||
'excerpt' => $post->excerpt,
|
||||
'body' => $post->body,
|
||||
'cover_image' => $post->cover_image,
|
||||
'category' => $post->category,
|
||||
'tags' => $post->tags ?? [],
|
||||
'is_featured' => $post->is_featured,
|
||||
'is_published' => $post->published_at !== null,
|
||||
// datetime-local value, in the app timezone
|
||||
'published_at' => $post->published_at?->format('Y-m-d\TH:i'),
|
||||
'status' => $post->status(),
|
||||
],
|
||||
'categories' => $this->labels->categories(),
|
||||
'known_tags' => $this->labels->names(PostLabels::TAG),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The post as a visitor will see it, also for drafts and scheduled posts. */
|
||||
public function preview(string $post): JsonResponse
|
||||
{
|
||||
$post = Post::query()->findOrFail($post);
|
||||
|
||||
return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $post): JsonResponse
|
||||
{
|
||||
$post = Post::query()->findOrFail($post);
|
||||
abort_unless($this->mayTouch($post), 403);
|
||||
app(AuditTrail::class)->about($post);
|
||||
|
||||
$post->update($this->validated($request, $post));
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
/** Puts a post on the site, or takes it off again (a draft) without opening it. */
|
||||
public function online(Request $request, string $post): JsonResponse
|
||||
{
|
||||
$post = Post::query()->findOrFail($post);
|
||||
$request->validate(['online' => ['required', 'boolean']]);
|
||||
app(AuditTrail::class)->about($post);
|
||||
|
||||
$post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]);
|
||||
|
||||
return response()->json(['status' => $post->status()]);
|
||||
}
|
||||
|
||||
public function destroy(string $post): JsonResponse
|
||||
{
|
||||
$post = Post::query()->findOrFail($post);
|
||||
abort_unless($this->mayTouch($post), 403);
|
||||
app(AuditTrail::class)->about($post);
|
||||
|
||||
$post->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the post form and turns it into model attributes.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function validated(Request $request, ?Post $post = null): array
|
||||
{
|
||||
$request->validate([
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(Names::table('posts'), 'slug')->ignore($post?->id)],
|
||||
'excerpt' => ['nullable', 'string', 'max:500'],
|
||||
'body' => ['required', 'string'],
|
||||
'cover_image' => ['nullable', 'string', 'max:2048'],
|
||||
'category' => ['nullable', 'string', 'max:60'],
|
||||
'tags' => ['array', 'max:20'],
|
||||
'tags.*' => ['nullable', 'string', 'max:40'],
|
||||
'is_featured' => ['boolean'],
|
||||
'is_published' => ['boolean'],
|
||||
'published_at' => ['nullable', 'date'],
|
||||
], [
|
||||
'slug.regex' => 'Use only lowercase letters, numbers and dashes.',
|
||||
]);
|
||||
|
||||
$title = $request->string('title')->trim()->toString();
|
||||
$slug = $request->string('slug')->trim()->toString();
|
||||
|
||||
// Publishing without a date means "now"; a date in the future schedules the post.
|
||||
// Who may not publish only gets a draft, and a post that was live is not touched
|
||||
// (mayTouch refused that before we got here).
|
||||
$publishedAt = null;
|
||||
if ($request->boolean('is_published') && Gate::allows('posts.publish')) {
|
||||
$date = $request->string('published_at')->toString();
|
||||
$publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now());
|
||||
}
|
||||
|
||||
return [
|
||||
'title' => $title,
|
||||
'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id),
|
||||
'excerpt' => $this->nullableString($request, 'excerpt'),
|
||||
'body' => $request->string('body')->toString(),
|
||||
'cover_image' => $this->nullableString($request, 'cover_image'),
|
||||
'category' => $this->nullableString($request, 'category'),
|
||||
'tags' => array_values(array_filter(array_map(
|
||||
fn (mixed $tag) => is_string($tag) ? trim($tag) : '',
|
||||
$request->array('tags'),
|
||||
))),
|
||||
'is_featured' => $request->boolean('is_featured'),
|
||||
'published_at' => $publishedAt,
|
||||
];
|
||||
}
|
||||
|
||||
private function mayTouch(Post $post): bool
|
||||
{
|
||||
return $post->published_at === null || Gate::allows('posts.publish');
|
||||
}
|
||||
|
||||
private function nullableString(Request $request, string $key): ?string
|
||||
{
|
||||
$value = $request->string($key)->trim()->toString();
|
||||
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Posts;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* The categories and tags of the posts, for managing them in one place. A category is the
|
||||
* `category` of a post and a tag an entry of its `tags`: a new one can simply be typed in a post.
|
||||
* One that is made by hand, before any post uses it, is a row of `post_labels`; that table only
|
||||
* remembers names to offer in the post form, a post never points to it.
|
||||
*
|
||||
* Renaming to a name that is already in use merges the two. Names are compared as written:
|
||||
* "Laravel" and "laravel" are two, which is how to merge them.
|
||||
*/
|
||||
class PostLabels
|
||||
{
|
||||
public const CATEGORY = 'category';
|
||||
|
||||
public const TAG = 'tag';
|
||||
|
||||
/** @var list<Closure(): iterable<string>> */
|
||||
private array $suggestions = [];
|
||||
|
||||
/** A site offers more categories in the post form, for instance the titles of its services. */
|
||||
public function suggestCategories(Closure $source): void
|
||||
{
|
||||
$this->suggestions[] = $source;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the post form offers as category: the suggestions of the site, the configured ones,
|
||||
* and whatever is in use or was made by hand.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function categories(): array
|
||||
{
|
||||
$suggested = [];
|
||||
|
||||
foreach ($this->suggestions as $source) {
|
||||
array_push($suggested, ...array_values([...$source()]));
|
||||
}
|
||||
|
||||
return array_values(array_unique([...$suggested, ...array_values((array) config('manager.posts.categories', [])), ...$this->names(self::CATEGORY)]));
|
||||
}
|
||||
|
||||
private function table(): string
|
||||
{
|
||||
return Names::table('post_labels');
|
||||
}
|
||||
|
||||
/**
|
||||
* Every category and tag, the ones made by hand included, with the number of posts (drafts
|
||||
* included) that use it.
|
||||
*
|
||||
* @return array{categories: list<array{name: string, posts: int}>, tags: list<array{name: string, posts: int}>}
|
||||
*/
|
||||
public function overview(): array
|
||||
{
|
||||
$categories = [];
|
||||
$tags = [];
|
||||
|
||||
foreach (Post::query()->get(['id', 'category', 'tags']) as $post) {
|
||||
if ($post->category !== null && $post->category !== '') {
|
||||
$categories[$post->category] = ($categories[$post->category] ?? 0) + 1;
|
||||
}
|
||||
|
||||
foreach (array_unique($this->tagsOf($post)) as $tag) {
|
||||
$tags[$tag] = ($tags[$tag] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (DB::table($this->table())->get(['type', 'name']) as $row) {
|
||||
if (! is_string($row->name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($row->type === self::CATEGORY) {
|
||||
$categories[$row->name] ??= 0;
|
||||
} else {
|
||||
$tags[$row->name] ??= 0;
|
||||
}
|
||||
}
|
||||
|
||||
return ['categories' => $this->listed($categories), 'tags' => $this->listed($tags)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The names of all categories or tags, to offer in the post form.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function names(string $type): array
|
||||
{
|
||||
return array_column($this->overview()[$type === self::CATEGORY ? 'categories' : 'tags'], 'name');
|
||||
}
|
||||
|
||||
/** Makes a category or tag that no post uses yet. False when the name is already there. */
|
||||
public function create(string $type, string $name): bool
|
||||
{
|
||||
if (in_array($name, $this->names($type), true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DB::table($this->table())->insert(['type' => $type, 'name' => $name, 'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Gives every post with the label the new name. Returns how many posts changed. */
|
||||
public function rename(string $type, string $from, string $to): int
|
||||
{
|
||||
if ($from === $to) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The name that was made by hand moves along, unless the new name is there already.
|
||||
$made = DB::table($this->table())->where('type', $type);
|
||||
if ((clone $made)->where('name', $to)->exists()) {
|
||||
(clone $made)->where('name', $from)->delete();
|
||||
} else {
|
||||
(clone $made)->where('name', $from)->update(['name' => $to, 'updated_at' => now()]);
|
||||
}
|
||||
|
||||
return $type === self::CATEGORY
|
||||
? Post::query()->where('category', $from)->update(['category' => $to])
|
||||
: $this->changeTags($from, $to);
|
||||
}
|
||||
|
||||
/** Takes the label off every post; the posts stay. Returns how many posts changed. */
|
||||
public function remove(string $type, string $name): int
|
||||
{
|
||||
DB::table($this->table())->where('type', $type)->where('name', $name)->delete();
|
||||
|
||||
return $type === self::CATEGORY
|
||||
? Post::query()->where('category', $name)->update(['category' => null])
|
||||
: $this->changeTags($name, null);
|
||||
}
|
||||
|
||||
/** Replaces a tag in every post that has it, or takes it out when $to is null. */
|
||||
private function changeTags(string $from, ?string $to): int
|
||||
{
|
||||
return DB::transaction(function () use ($from, $to) {
|
||||
$changed = 0;
|
||||
|
||||
foreach (Post::query()->whereNotNull('tags')->get() as $post) {
|
||||
$tags = $this->tagsOf($post);
|
||||
|
||||
if (! in_array($from, $tags, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$new = [];
|
||||
foreach ($tags as $tag) {
|
||||
$tag = $tag === $from ? $to : $tag;
|
||||
|
||||
// A post that had both names keeps the tag once.
|
||||
if ($tag !== null && ! in_array($tag, $new, true)) {
|
||||
$new[] = $tag;
|
||||
}
|
||||
}
|
||||
|
||||
$post->update(['tags' => $new]);
|
||||
$changed++;
|
||||
}
|
||||
|
||||
return $changed;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function tagsOf(Post $post): array
|
||||
{
|
||||
return array_values(array_filter(is_array($post->tags) ? $post->tags : [], fn (mixed $tag) => is_string($tag) && $tag !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, int> $counts
|
||||
* @return list<array{name: string, posts: int}>
|
||||
*/
|
||||
private function listed(array $counts): array
|
||||
{
|
||||
$names = array_map(fn (int|string $name) => (string) $name, array_keys($counts));
|
||||
natcasesort($names);
|
||||
|
||||
return array_values(array_map(fn (string $name) => ['name' => $name, 'posts' => $counts[$name]], $names));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Posts;
|
||||
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\MediaUsage;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class PostsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'posts';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Posts';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['posts', 'post_labels'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('posts.view', 'See the posts, drafts included', 'Posts'),
|
||||
new Permission('posts.write', 'Write posts: create drafts and change them', 'Posts', needs: ['posts.view']),
|
||||
new Permission('posts.publish', 'Publish, schedule and unpublish posts, and change posts that are live', 'Posts', needs: ['posts.view', 'posts.write']),
|
||||
new Permission('posts.delete', 'Delete posts (one that is live only together with publishing)', 'Posts', needs: ['posts.view']),
|
||||
new Permission('posts.labels', 'Manage the categories and tags: make them, and rename, merge and remove them on all posts', 'Posts', needs: ['posts.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view', 'simple' => true, 'hint' => 'Write and put news on your website'],
|
||||
['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'],
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'posts.store' => ['Created a post'],
|
||||
'posts.update' => ['Changed a post'],
|
||||
'posts.online' => ['Put a post on the site, or took it off', ['online']],
|
||||
'posts.destroy' => ['Deleted a post'],
|
||||
'labels.store' => ['Made a category or tag', ['type', 'name']],
|
||||
'labels.update' => ['Renamed a category or tag', ['type', 'name', 'new_name']],
|
||||
'labels.destroy' => ['Removed a category or tag', ['type', 'name']],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return [
|
||||
'posts.index' => 'Opened the posts',
|
||||
'posts.create' => 'Opened the form for a new post',
|
||||
'posts.edit' => 'Opened a post',
|
||||
'posts.preview' => 'Opened the preview of a post',
|
||||
'labels.index' => 'Opened the categories and tags',
|
||||
];
|
||||
}
|
||||
|
||||
/** Where the media library looks for the use of a file: the texts of the posts. */
|
||||
public function boot(): void
|
||||
{
|
||||
app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt', 'cover_image'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt', 'cover_image']))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?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('posts'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('title');
|
||||
$table->string('slug')->unique();
|
||||
$table->string('excerpt', 500)->nullable();
|
||||
$table->longText('body');
|
||||
$table->string('cover_image', 2048)->nullable();
|
||||
$table->string('category', 60)->nullable();
|
||||
$table->json('tags')->nullable();
|
||||
$table->boolean('is_featured')->default(false);
|
||||
// null = draft; a future date = scheduled
|
||||
$table->timestamp('published_at')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
// Categories and tags that were made by hand, so one can exist before a post uses it.
|
||||
// The ones a post uses are in the post itself; this only remembers names to offer.
|
||||
Tables::create(Names::table('post_labels'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('type', 10);
|
||||
$table->string('name', 60);
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['type', 'name']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
|
||||
Schema::dropIfExists(Names::table('post_labels'));
|
||||
Schema::dropIfExists(Names::table('posts'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Posts\LabelController;
|
||||
use IriksIT\Manager\Modules\Posts\PostController;
|
||||
|
||||
Route::get('/posts', [PostController::class, 'index'])->name('posts.index')->middleware('can:posts.view');
|
||||
Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create')->middleware('can:posts.write');
|
||||
Route::post('/posts', [PostController::class, 'store'])->name('posts.store')->middleware('can:posts.write');
|
||||
Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit')->middleware('can:posts.write')->whereNumber('post');
|
||||
Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('posts.preview')->middleware('can:posts.view')->whereNumber('post');
|
||||
Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update')->middleware('can:posts.write')->whereNumber('post');
|
||||
Route::put('/posts/{post}/online', [PostController::class, 'online'])->name('posts.online')->middleware('can:posts.publish')->whereNumber('post');
|
||||
Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy')->middleware('can:posts.delete')->whereNumber('post');
|
||||
|
||||
// The name of a label travels in the body, not the address: it can hold anything.
|
||||
Route::middleware('can:posts.labels')->group(function () {
|
||||
Route::get('/labels', [LabelController::class, 'index'])->name('labels.index');
|
||||
Route::post('/labels', [LabelController::class, 'store'])->name('labels.store');
|
||||
Route::put('/labels', [LabelController::class, 'update'])->name('labels.update');
|
||||
Route::delete('/labels', [LabelController::class, 'destroy'])->name('labels.destroy');
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Resources;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Fields;
|
||||
use IriksIT\Manager\Support\Resources;
|
||||
|
||||
class ResourceController
|
||||
{
|
||||
public function index(string $resource): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'view');
|
||||
$page = Resources::query($def)->paginate($def['per_page']);
|
||||
|
||||
return response()->json([
|
||||
'resource' => $this->describe($def),
|
||||
'rows' => $page->getCollection()->map(fn (Model $model) => Resources::row($def, $model))->values(),
|
||||
'current_page' => $page->currentPage(),
|
||||
'last_page' => $page->lastPage(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function create(string $resource): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'manage');
|
||||
|
||||
return response()->json(['resource' => $this->describe($def), 'record' => ['id' => null, 'values' => Fields::values($def['fields'], [])]]);
|
||||
}
|
||||
|
||||
public function edit(string $resource, string $id): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'manage');
|
||||
|
||||
return response()->json(['resource' => $this->describe($def), 'record' => Resources::row($def, $this->record($def, $id))]);
|
||||
}
|
||||
|
||||
public function store(Request $request, string $resource): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'manage');
|
||||
$model = Resources::save($def, null, $this->values($request, $def));
|
||||
app(AuditTrail::class)->about($model);
|
||||
|
||||
return response()->json(['record' => Resources::row($def, $model)], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $resource, string $id): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'manage');
|
||||
$model = Resources::save($def, $this->record($def, $id), $this->values($request, $def));
|
||||
app(AuditTrail::class)->about($model);
|
||||
|
||||
return response()->json(['record' => Resources::row($def, $model)]);
|
||||
}
|
||||
|
||||
public function destroy(string $resource, string $id): JsonResponse
|
||||
{
|
||||
$def = $this->resource($resource, 'manage');
|
||||
$model = $this->record($def, $id);
|
||||
app(AuditTrail::class)->about($model);
|
||||
$model->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function resource(string $key, string $ability): array
|
||||
{
|
||||
$def = Resources::find($key);
|
||||
abort_if($def === null, 404);
|
||||
Gate::authorize($key.'.'.$ability);
|
||||
|
||||
return $def;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $def */
|
||||
private function record(array $def, string $id): Model
|
||||
{
|
||||
return Resources::record($def, $id) ?? abort(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $def
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function values(Request $request, array $def): array
|
||||
{
|
||||
$data = $request->validate(Fields::rules($def['fields']));
|
||||
|
||||
return Fields::clean($def['fields'], $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $def
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function describe(array $def): array
|
||||
{
|
||||
return [
|
||||
'key' => $def['key'], 'label' => $def['label'], 'singular' => $def['singular'], 'simple_label' => $def['simple_label'], 'simple_singular' => $def['simple_singular'], 'columns' => $def['columns'],
|
||||
'fields' => Fields::described($def['fields']), 'can_manage' => Gate::allows($def['key'].'.manage'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Resources;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
use IriksIT\Manager\Support\Resources;
|
||||
|
||||
/**
|
||||
* The lists a site defines in config (`manager.resources`): menu item, permissions and screens for each, with
|
||||
* nothing registered when there are none.
|
||||
*/
|
||||
class ResourcesModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'resources';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Resources';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['records'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
$permissions = [];
|
||||
|
||||
foreach (Resources::all() as $key => $resource) {
|
||||
$permissions[] = new Permission($key.'.view', __('See :label', ['label' => $resource['label']]), $resource['label']);
|
||||
$permissions[] = new Permission($key.'.manage', __('Add, change and delete :label', ['label' => $resource['label']]), $resource['label'], needs: [$key.'.view']);
|
||||
}
|
||||
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'simple_label' => $resource['simple_label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view', 'simple' => true, 'hint' => $resource['hint']],
|
||||
Resources::all(),
|
||||
));
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'records.store' => ['Added a record'],
|
||||
'records.update' => ['Changed a record'],
|
||||
'records.destroy' => ['Removed a record'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['records.index' => 'Opened a list', 'records.create' => 'Opened the form for a new record', 'records.edit' => 'Opened a record'];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
Tables::create(Names::table('records'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('resource', 40)->index();
|
||||
$table->json('data')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('records'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Resources\ResourceController;
|
||||
|
||||
// Every resource the site defined shares these routes; the controller checks `<resource>.view` and `<resource>.manage`.
|
||||
Route::prefix('/records/{resource}')->where(['resource' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+'])->group(function () {
|
||||
Route::get('/', [ResourceController::class, 'index'])->name('records.index');
|
||||
Route::get('/create', [ResourceController::class, 'create'])->name('records.create');
|
||||
Route::post('/', [ResourceController::class, 'store'])->name('records.store');
|
||||
Route::get('/{id}/edit', [ResourceController::class, 'edit'])->name('records.edit');
|
||||
Route::put('/{id}', [ResourceController::class, 'update'])->name('records.update');
|
||||
Route::delete('/{id}', [ResourceController::class, 'destroy'])->name('records.destroy');
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Reviews;
|
||||
|
||||
use IriksIT\Manager\Models\Review;
|
||||
|
||||
class ReviewsController
|
||||
{
|
||||
/** First opzet: lists the records as JSON. The screens come with the frontend. */
|
||||
public function index()
|
||||
{
|
||||
return response()->json(Review::query()->latest()->paginate(25));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Reviews;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class ReviewsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'reviews';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Reviews';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['reviews'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('reviews.manage', 'Manage the reviews', 'Site content'),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Reviews', 'route' => Names::route('reviews.index'), 'permission' => 'reviews.manage'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['reviews.index' => 'Opened the reviews'];
|
||||
}
|
||||
}
|
||||
@@ -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('reviews'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('author');
|
||||
$table->string('place')->nullable();
|
||||
$table->unsignedTinyInteger('rating')->nullable();
|
||||
$table->text('body');
|
||||
$table->boolean('is_visible')->default(true);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('reviews'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Reviews\ReviewsController;
|
||||
|
||||
Route::get('/reviews', [ReviewsController::class, 'index'])->name('reviews.index')->middleware('can:reviews.manage');
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Revisions;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Revision;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Revisions;
|
||||
|
||||
class RevisionController
|
||||
{
|
||||
public function index(string $type, string $id): JsonResponse
|
||||
{
|
||||
[$config, $model] = $this->find($type, $id, 'view');
|
||||
|
||||
$revisions = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->orderByDesc('id')->limit(100)->get();
|
||||
|
||||
return response()->json([
|
||||
'revisions' => $revisions->map(fn (Revision $revision, int $position) => [
|
||||
'id' => $revision->id,
|
||||
'created_at' => $revision->created_at,
|
||||
'user' => $revision->user_name,
|
||||
'changed' => $revision->changed ?? [],
|
||||
'current' => $position === 0,
|
||||
// What the changed attributes were then, shortened: enough to see what an old version said.
|
||||
'values' => collect($revision->changed ?? [])->mapWithKeys(fn (string $key) => [$key => $this->shorten($revision->data[$key] ?? null)])->all(),
|
||||
])->values(),
|
||||
'can_restore' => Gate::allows('revisions.restore') && Gate::allows($config['restore']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function restore(string $type, string $id, string $revision): JsonResponse
|
||||
{
|
||||
[$config, $model] = $this->find($type, $id, 'restore');
|
||||
$revision = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->whereKey($revision)->firstOrFail();
|
||||
|
||||
// A post that is on the site is only changed by someone who may publish.
|
||||
abort_if($model instanceof Post && $model->isPublished() && Gate::denies('posts.publish'), 403);
|
||||
|
||||
app(AuditTrail::class)->about($model);
|
||||
Revisions::restore($model, $revision, $config);
|
||||
|
||||
return response()->json(['restored' => true]);
|
||||
}
|
||||
|
||||
/** @return array{0: array{model: class-string<Model>, view: string, restore: string, except: list<string>}, 1: Model} */
|
||||
private function find(string $type, string $id, string $ability): array
|
||||
{
|
||||
$config = Revisions::types()[$type] ?? null;
|
||||
abort_if($config === null, 404);
|
||||
Gate::authorize($config[$ability]);
|
||||
|
||||
return [$config, $config['model']::query()->findOrFail($id)];
|
||||
}
|
||||
|
||||
private function shorten(mixed $value): mixed
|
||||
{
|
||||
$text = is_scalar($value) || $value === null ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
return mb_strlen($text) > 300 ? mb_substr($text, 0, 300).'…' : $text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Revisions;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
use IriksIT\Manager\Support\Revisions;
|
||||
|
||||
/** The history of posts and pages (and of what a site adds): see an earlier state and put it back. */
|
||||
class RevisionsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'revisions';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'History';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['revisions'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('revisions.view', 'See the history of posts and pages', 'History'),
|
||||
new Permission('revisions.restore', 'Put an earlier version of a post or page back', 'History', needs: ['revisions.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return ['revisions.restore' => ['Put an earlier version back']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['revisions.index' => 'Opened the history of a text'];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Revisions::listen();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?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('revisions'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('type', 40);
|
||||
$table->unsignedBigInteger('subject_id');
|
||||
// Who saved it: no foreign key, so the history stays when an account is removed.
|
||||
$table->unsignedBigInteger('user_id')->nullable();
|
||||
$table->string('user_name')->nullable();
|
||||
$table->json('data');
|
||||
$table->json('changed')->nullable();
|
||||
$table->dateTime('created_at');
|
||||
|
||||
$table->index(['type', 'subject_id', 'id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('revisions'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Revisions\RevisionController;
|
||||
|
||||
// `{type}` is a key of Support\Revisions::types(); the controller checks the permissions of that type too.
|
||||
Route::middleware('can:revisions.view')->prefix('/revisions/{type}/{id}')->where(['type' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+', 'revision' => '[0-9]+'])->group(function () {
|
||||
Route::get('/', [RevisionController::class, 'index'])->name('revisions.index');
|
||||
Route::post('/{revision}/restore', [RevisionController::class, 'restore'])->name('revisions.restore')->middleware('can:revisions.restore');
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Settings;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Settings\Checks;
|
||||
use IriksIT\Manager\Support\Settings\Definitions;
|
||||
use IriksIT\Manager\Support\Settings\EnvFile;
|
||||
use IriksIT\Manager\Support\Settings\Store;
|
||||
use IriksIT\Manager\Support\Settings\Writer;
|
||||
|
||||
/**
|
||||
* The settings screen. Only in the whole face of the manager (a simple account gets a 403, whatever its rights). What changes
|
||||
* how a password or a file travels (secrets, addresses, accounts, disks) also needs `settings.secrets` and the password of the
|
||||
* account that saves it. A secret is never sent to the browser: it is only said to be set.
|
||||
*/
|
||||
class SettingsController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Definitions $definitions,
|
||||
private readonly Store $store,
|
||||
private readonly EnvFile $env,
|
||||
private readonly Writer $writer,
|
||||
private readonly Checks $checks,
|
||||
private readonly ModuleRegistry $modules,
|
||||
private readonly Menu $menu,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
|
||||
$groups = [];
|
||||
$origin = [];
|
||||
|
||||
foreach ($this->definitions->all() as $key => $definition) {
|
||||
if (! $this->mayChange($request, $definition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = config($key);
|
||||
|
||||
$origin[__($definition['group'])] = $definition['group'];
|
||||
$groups[__($definition['group'])][] = [
|
||||
'key' => $key,
|
||||
'label' => __($definition['label']),
|
||||
'type' => $definition['type'],
|
||||
'help' => $definition['help'] === null ? null : __($definition['help']),
|
||||
'options' => $definition['options'],
|
||||
'sensitive' => $definition['sensitive'],
|
||||
// A secret says only whether it is set.
|
||||
'value' => $definition['type'] === 'secret' ? null : $value,
|
||||
'set' => $definition['type'] === 'secret' ? filled($value) : null,
|
||||
'saved' => $this->store->has($key),
|
||||
];
|
||||
}
|
||||
|
||||
$mayTry = Gate::forUser($request->user())->allows('settings.secrets');
|
||||
|
||||
return response()->json([
|
||||
'groups' => collect($groups)->map(fn (array $items, string $name) => ['name' => $name, 'items' => $items, 'check' => $mayTry && $this->checks->has($origin[$name])])->values(),
|
||||
'write_env' => (bool) config('manager.settings.write_env'),
|
||||
'env_writable' => $this->env->writable(),
|
||||
'config_cached' => app()->configurationIsCached(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
$request->validate(['values' => ['present', 'array'], 'reset' => ['nullable', 'array'], 'reset.*' => ['string'], 'password' => ['nullable', 'string', 'max:200']]);
|
||||
|
||||
$changes = [];
|
||||
$sensitive = false;
|
||||
|
||||
foreach ($request->array('values') as $key => $raw) {
|
||||
$definition = $this->definitions->find((string) $key);
|
||||
|
||||
if ($definition === null || ! $this->mayChange($request, $definition)) {
|
||||
throw ValidationException::withMessages(['values' => __('This setting does not exist or you may not change it.')]);
|
||||
}
|
||||
|
||||
// A secret that is left empty is left alone (the browser sends an empty field as null): clearing one is `reset`.
|
||||
if ($definition['type'] === 'secret' && ($raw === '' || $raw === null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$value = $raw === null ? null : $this->definitions->cast($definition, $raw);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages(['values.'.$key => __('This value is not valid.')]);
|
||||
}
|
||||
|
||||
if ($value !== null && $value === config($key) && ! $this->store->has($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$changes[$key] = $value;
|
||||
$sensitive = $sensitive || $definition['sensitive'];
|
||||
}
|
||||
|
||||
// `reset`: back to what the config (and .env) says.
|
||||
foreach ($request->array('reset') as $key) {
|
||||
$definition = $this->definitions->find((string) $key);
|
||||
|
||||
if ($definition === null || ! $this->mayChange($request, $definition)) {
|
||||
throw ValidationException::withMessages(['reset' => __('This setting does not exist or you may not change it.')]);
|
||||
}
|
||||
|
||||
$changes[$key] = null;
|
||||
$sensitive = $sensitive || $definition['sensitive'];
|
||||
}
|
||||
|
||||
if ($sensitive && ! Hash::check((string) $request->input('password'), (string) $request->user()->getAuthPassword())) {
|
||||
throw ValidationException::withMessages(['password' => __('Type your own password to change this.')]);
|
||||
}
|
||||
|
||||
$result = $this->writer->apply($changes, $request->user()->getAuthIdentifier());
|
||||
|
||||
return response()->json([
|
||||
'saved' => true,
|
||||
'changed' => count($changes),
|
||||
...$result,
|
||||
'migrate' => $this->pendingMigrations(array_keys($changes)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Writes the compiled file again and empties what caches the old values. */
|
||||
public function refresh(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
|
||||
$written = $this->writer->refresh();
|
||||
|
||||
return response()->json(['refreshed' => true, 'file_written' => $written]);
|
||||
}
|
||||
|
||||
/** Tries the connection of one group of settings with what is saved. Needs `settings.secrets`: it uses the keys. */
|
||||
public function check(Request $request): JsonResponse
|
||||
{
|
||||
$this->onlyFull($request);
|
||||
abort_unless(Gate::forUser($request->user())->allows('settings.secrets'), 403);
|
||||
|
||||
$group = (string) $request->validate(['group' => ['required', 'string', 'max:100']])['group'];
|
||||
// The name that comes in is the translated one, as the screen shows it; the checks are keyed by the untranslated one.
|
||||
$key = collect($this->definitions->all())->pluck('group')->unique()->first(fn (string $name) => __($name) === $group);
|
||||
|
||||
abort_unless($key !== null && $this->checks->has($key), 404);
|
||||
|
||||
return response()->json($this->checks->run($key));
|
||||
}
|
||||
|
||||
private function onlyFull(Request $request): void
|
||||
{
|
||||
abort_if($this->menu->view($request->user()) === Menu::SIMPLE, 403);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $definition */
|
||||
private function mayChange(Request $request, array $definition): bool
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return (! $definition['sensitive'] || Gate::forUser($user)->allows('settings.secrets'))
|
||||
&& ($definition['permission'] === null || Gate::forUser($user)->allows($definition['permission']));
|
||||
}
|
||||
|
||||
/**
|
||||
* The parts that were switched on and miss a table: the screen tells to run `php artisan migrate`.
|
||||
*
|
||||
* @param list<string> $keys
|
||||
* @return list<string>
|
||||
*/
|
||||
private function pendingMigrations(array $keys): array
|
||||
{
|
||||
$labels = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (! str_starts_with($key, 'manager.modules.') || ! config($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($this->modules->all() as $module) {
|
||||
if ('manager.modules.'.$module->key() === $key && collect($module->tables())->contains(fn (string $table) => ! Schema::hasTable(Names::table($table)))) {
|
||||
$labels[] = $module->label();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $labels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Settings;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* The settings screen: which parts and features are on, and the keys and addresses of integrations, all changeable from the
|
||||
* manager by an account with the right, in the whole face of the manager only. A change is saved (secrets encrypted) and works at
|
||||
* once; see Support\Settings.
|
||||
*/
|
||||
class SettingsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'settings';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Settings';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['settings'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('settings.manage', 'Switch parts and features on or off and change settings', 'Settings'),
|
||||
new Permission('settings.secrets', 'Change keys, passwords and addresses of integrations', 'Settings', needs: ['settings.manage']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Settings', 'route' => Names::route('settings.index'), 'permission' => 'settings.manage', 'icon' => 'cog', 'simple' => false]];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return ['settings.update' => ['Changed the settings'], 'settings.refresh' => ['Refreshed the settings'], 'settings.check' => ['Tried a connection of the settings']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['settings.index' => 'Opened the settings'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?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('settings'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('key', 150)->unique();
|
||||
// JSON; a secret is encrypted.
|
||||
$table->text('value')->nullable();
|
||||
$table->boolean('is_secret')->default(false);
|
||||
$table->unsignedBigInteger('updated_by')->nullable();
|
||||
$table->dateTime('created_at')->nullable();
|
||||
$table->dateTime('updated_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('settings'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Settings\SettingsController;
|
||||
|
||||
Route::middleware('can:settings.manage')->group(function () {
|
||||
Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
|
||||
Route::put('/settings', [SettingsController::class, 'update'])->name('settings.update');
|
||||
Route::post('/settings/check', [SettingsController::class, 'check'])->name('settings.check');
|
||||
Route::post('/settings/refresh', [SettingsController::class, 'refresh'])->name('settings.refresh');
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Sharing;
|
||||
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use IriksIT\Manager\Contracts\Sharer;
|
||||
use IriksIT\Manager\Models\SocialConnection;
|
||||
use IriksIT\Manager\Support\Sharing\ShareContent;
|
||||
use IriksIT\Manager\Support\Sharing\SharedPost;
|
||||
use IriksIT\Manager\Support\Sharing\SharingException;
|
||||
|
||||
/**
|
||||
* Posts on the owner's own LinkedIn profile, through the product "Share on LinkedIn" (scope `w_member_social`). The app of the
|
||||
* site needs that product and "Sign In with LinkedIn using OpenID Connect". The post is an article card: LinkedIn reads the
|
||||
* title, description and picture of the page itself.
|
||||
*/
|
||||
class LinkedInSharer implements Sharer
|
||||
{
|
||||
public const NAME = 'linkedin';
|
||||
|
||||
public const SCOPE = 'openid profile w_member_social';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'LinkedIn';
|
||||
}
|
||||
|
||||
public function maxLength(): int
|
||||
{
|
||||
return 2900;
|
||||
}
|
||||
|
||||
public function canConnect(): bool
|
||||
{
|
||||
return $this->setting('client_id') !== '' && $this->setting('client_secret') !== '';
|
||||
}
|
||||
|
||||
public function missing(): string
|
||||
{
|
||||
return __('LinkedIn: client id and client secret');
|
||||
}
|
||||
|
||||
public function connection(): ?SocialConnection
|
||||
{
|
||||
return SocialConnection::query()->find(self::NAME);
|
||||
}
|
||||
|
||||
public function accountName(): ?string
|
||||
{
|
||||
return $this->connection()?->account_name;
|
||||
}
|
||||
|
||||
public function authorizationUrl(string $state, string $redirectUri, string $verifier = ''): string
|
||||
{
|
||||
return $this->setting('auth_url').'/authorization?'.http_build_query([
|
||||
'response_type' => 'code',
|
||||
'client_id' => $this->setting('client_id'),
|
||||
'redirect_uri' => $redirectUri,
|
||||
'state' => $state,
|
||||
'scope' => self::SCOPE,
|
||||
]);
|
||||
}
|
||||
|
||||
public function connect(string $code, string $redirectUri, string $verifier = ''): SocialConnection
|
||||
{
|
||||
if (! $this->canConnect()) {
|
||||
throw new SharingException(__('The LinkedIn app is not set up: fill in its client id and client secret.'));
|
||||
}
|
||||
|
||||
$response = $this->send(fn () => Http::asForm()->acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)
|
||||
->post($this->setting('auth_url').'/accessToken', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $code,
|
||||
'redirect_uri' => $redirectUri,
|
||||
'client_id' => $this->setting('client_id'),
|
||||
'client_secret' => $this->setting('client_secret'),
|
||||
]));
|
||||
|
||||
$token = $response->json('access_token');
|
||||
|
||||
if ($response->failed() || ! is_string($token) || $token === '') {
|
||||
throw new SharingException(__('LinkedIn did not give a token').$this->reason($response));
|
||||
}
|
||||
|
||||
// Who the site will post as.
|
||||
$me = $this->send(fn () => $this->api($token)->get($this->setting('userinfo_url')));
|
||||
$id = $me->json('sub');
|
||||
|
||||
if ($me->failed() || ! is_string($id) || $id === '') {
|
||||
throw new SharingException(__('LinkedIn did not say whose account this is').$this->reason($me).' '.__('Check that the app has the product "Sign In with LinkedIn using OpenID Connect".'));
|
||||
}
|
||||
|
||||
$name = $me->json('name');
|
||||
$expiresIn = $response->json('expires_in');
|
||||
$refreshToken = $response->json('refresh_token');
|
||||
$refreshExpiresIn = $response->json('refresh_token_expires_in');
|
||||
|
||||
return SocialConnection::query()->updateOrCreate(['name' => self::NAME], [
|
||||
'access_token' => $token,
|
||||
'expires_at' => is_numeric($expiresIn) ? now()->addSeconds((int) $expiresIn) : null,
|
||||
'refresh_token' => is_string($refreshToken) && $refreshToken !== '' ? $refreshToken : null,
|
||||
'refresh_token_expires_at' => is_numeric($refreshExpiresIn) ? now()->addSeconds((int) $refreshExpiresIn) : null,
|
||||
'account_id' => 'urn:li:person:'.$id,
|
||||
'account_name' => is_string($name) && $name !== '' ? mb_substr($name, 0, 200) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function disconnect(): void
|
||||
{
|
||||
SocialConnection::query()->whereKey(self::NAME)->delete();
|
||||
}
|
||||
|
||||
public function publish(ShareContent $content): SharedPost
|
||||
{
|
||||
$connection = $this->connection();
|
||||
|
||||
if (! $connection instanceof SocialConnection || ! is_string($connection->account_id)) {
|
||||
throw new SharingException(__('LinkedIn is not connected.'));
|
||||
}
|
||||
|
||||
if ($connection->expires_at !== null && $connection->expires_at->isPast()) {
|
||||
throw new SharingException(__('The connection with LinkedIn has expired. Connect again under Sharing.'));
|
||||
}
|
||||
|
||||
$token = $connection->access_token;
|
||||
|
||||
$response = $this->send(fn () => $this->api($token)->post($this->setting('base_url').'/posts', [
|
||||
'author' => $connection->account_id,
|
||||
'commentary' => self::escape($content->text),
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => ['feedDistribution' => 'MAIN_FEED', 'targetEntities' => [], 'thirdPartyDistributionChannels' => []],
|
||||
'content' => ['article' => ['source' => $content->url, 'title' => $content->title, 'description' => $content->description]],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
'isReshareDisabledByAuthor' => false,
|
||||
]));
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new SharingException(match ($response->status()) {
|
||||
401 => __('LinkedIn refused the connection. Connect again under Sharing.'),
|
||||
403 => __('LinkedIn does not allow this app to post. Check that it has the product "Share on LinkedIn".'),
|
||||
429 => __('LinkedIn says there were too many posts. Try again later.'),
|
||||
default => __('LinkedIn did not accept the post').$this->reason($response),
|
||||
});
|
||||
}
|
||||
|
||||
$id = $response->header('x-restli-id');
|
||||
$id = $id !== '' ? $id : $response->json('id');
|
||||
|
||||
if (! is_string($id) || $id === '') {
|
||||
// Posted, but LinkedIn did not say under which id: there is nothing to link to.
|
||||
return new SharedPost('unknown');
|
||||
}
|
||||
|
||||
return new SharedPost($id, 'https://www.linkedin.com/feed/update/'.rawurlencode($id).'/');
|
||||
}
|
||||
|
||||
private function api(string $token): PendingRequest
|
||||
{
|
||||
return Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(30)->withToken($token)->withHeaders([
|
||||
'LinkedIn-Version' => $this->setting('version'),
|
||||
'X-Restli-Protocol-Version' => '2.0.0',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(): Response $request
|
||||
*/
|
||||
private function send(callable $request): Response
|
||||
{
|
||||
try {
|
||||
return $request();
|
||||
} catch (ConnectionException) {
|
||||
throw new SharingException(__('LinkedIn could not be reached.'));
|
||||
}
|
||||
}
|
||||
|
||||
/** LinkedIn's own words about what went wrong, as the end of a sentence. Never holds a token. */
|
||||
private function reason(Response $response): string
|
||||
{
|
||||
$reason = $response->json('error_description') ?? $response->json('message');
|
||||
|
||||
return is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : " (HTTP {$response->status()}).";
|
||||
}
|
||||
|
||||
/**
|
||||
* LinkedIn reads the text of a post as its "little text format", where these characters mean something (mentions, hashtags,
|
||||
* templates). Escaped, they are shown as typed.
|
||||
*/
|
||||
public static function escape(string $text): string
|
||||
{
|
||||
return (string) preg_replace('/[\\\\|{}@\[\]()<>#*_~]/', '\\\\$0', $text);
|
||||
}
|
||||
|
||||
private function setting(string $key): string
|
||||
{
|
||||
$value = config("manager.sharing.linkedin.{$key}");
|
||||
|
||||
return is_string($value) ? trim($value) : '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Sharing;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\PostShare;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Sharing\PostSharing;
|
||||
use IriksIT\Manager\Support\Sharing\Sharers;
|
||||
use IriksIT\Manager\Support\Sharing\SharingException;
|
||||
|
||||
/**
|
||||
* The platforms the site shares posts on: connecting the owner's accounts (OAuth), the list of what was shared, and the
|
||||
* "Share now" button of a post. A token or secret never goes to a screen.
|
||||
*/
|
||||
class SharingController
|
||||
{
|
||||
private const STATE_KEY = 'manager.sharing.state.';
|
||||
|
||||
private const VERIFIER_KEY = 'manager.sharing.verifier.';
|
||||
|
||||
/** What the screen may be told after coming back from a platform: a code, never free text from the address. */
|
||||
private const NOTICES = ['connected', 'denied', 'failed', 'state'];
|
||||
|
||||
public function index(Request $request, Sharers $sharers): JsonResponse
|
||||
{
|
||||
$platforms = [];
|
||||
|
||||
foreach ($sharers->names() as $name) {
|
||||
$sharer = $sharers->for($name);
|
||||
$connection = $sharer->connection();
|
||||
|
||||
$platforms[] = [
|
||||
'platform' => $name,
|
||||
'label' => $sharer->label(),
|
||||
'can_connect' => $sharer->canConnect(),
|
||||
'missing' => $sharer->canConnect() ? null : $sharer->missing(),
|
||||
'connected' => $connection !== null,
|
||||
'account' => $sharer->accountName(),
|
||||
'expires_at' => $connection?->expires_at?->toIso8601String(),
|
||||
'callback_url' => route(Names::route('sharing.callback'), $name),
|
||||
];
|
||||
}
|
||||
|
||||
$notice = (string) $request->query('notice');
|
||||
|
||||
return response()->json([
|
||||
'live' => PostSharing::isLive(),
|
||||
'platforms' => $platforms,
|
||||
'notice' => in_array($notice, self::NOTICES, true) ? $notice : null,
|
||||
'shares' => PostShare::query()->with('post')->where('status', '!=', PostShare::PENDING)->latest('id')->limit(30)->get()
|
||||
->map(fn (PostShare $share) => [
|
||||
'id' => $share->id,
|
||||
'post_id' => $share->post_id,
|
||||
'post_title' => $share->post?->title,
|
||||
'platform' => $share->platform,
|
||||
'status' => $share->status,
|
||||
'dry_run' => (bool) $share->dry_run,
|
||||
'url' => $share->external_url,
|
||||
'error' => $share->error,
|
||||
'at' => ($share->shared_at ?? $share->updated_at)?->toIso8601String(),
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Sends the owner to the platform to give permission. */
|
||||
public function connect(Request $request, Sharers $sharers, string $platform): RedirectResponse
|
||||
{
|
||||
$sharer = $sharers->for($platform);
|
||||
|
||||
if (! $sharer->canConnect()) {
|
||||
return $this->back('failed');
|
||||
}
|
||||
|
||||
// The platform sends this value back; it proves the answer belongs to this login session.
|
||||
$state = Str::random(40);
|
||||
// A second secret that never leaves this site until the code is traded in (PKCE).
|
||||
$verifier = Str::random(64);
|
||||
$request->session()->put(self::STATE_KEY.$platform, $state);
|
||||
$request->session()->put(self::VERIFIER_KEY.$platform, $verifier);
|
||||
|
||||
return redirect()->away($sharer->authorizationUrl($state, route(Names::route('sharing.callback'), $platform), $verifier));
|
||||
}
|
||||
|
||||
/** Where the platform sends the owner back to, with a code or with an error. */
|
||||
public function callback(Request $request, Sharers $sharers, string $platform): RedirectResponse
|
||||
{
|
||||
$sharer = $sharers->for($platform);
|
||||
$expected = $request->session()->pull(self::STATE_KEY.$platform);
|
||||
$verifier = $request->session()->pull(self::VERIFIER_KEY.$platform);
|
||||
$state = $request->query('state');
|
||||
|
||||
if (! is_string($expected) || ! is_string($state) || ! hash_equals($expected, $state)) {
|
||||
return $this->back('state');
|
||||
}
|
||||
|
||||
if ($request->query('error') !== null) {
|
||||
return $this->back('denied');
|
||||
}
|
||||
|
||||
$code = $request->query('code');
|
||||
|
||||
if (! is_string($code) || $code === '') {
|
||||
return $this->back('failed');
|
||||
}
|
||||
|
||||
try {
|
||||
$sharer->connect($code, route(Names::route('sharing.callback'), $platform), is_string($verifier) ? $verifier : '');
|
||||
} catch (SharingException) {
|
||||
return $this->back('failed');
|
||||
}
|
||||
|
||||
return $this->back('connected');
|
||||
}
|
||||
|
||||
public function disconnect(Sharers $sharers, string $platform): JsonResponse
|
||||
{
|
||||
$sharers->for($platform)->disconnect();
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
/** How a post stands on every platform, for the panel on its screen. */
|
||||
public function post(Post $post, PostSharing $sharing): JsonResponse
|
||||
{
|
||||
return response()->json(['live' => PostSharing::isLive(), 'platforms' => $sharing->overview($post)]);
|
||||
}
|
||||
|
||||
public function share(Request $request, Post $post, Sharers $sharers, PostSharing $sharing): JsonResponse
|
||||
{
|
||||
$request->validate(['platform' => ['required', 'string', 'max:20']]);
|
||||
$platform = $request->string('platform')->toString();
|
||||
|
||||
abort_unless($sharers->has($platform), 422, __('This platform is not known.'));
|
||||
|
||||
try {
|
||||
$share = $sharing->shareNow($post, $platform);
|
||||
} catch (SharingException $e) {
|
||||
return response()->json(['message' => $e->getMessage()], 422);
|
||||
}
|
||||
|
||||
if ($share->status === PostShare::FAILED) {
|
||||
return response()->json(['message' => (string) $share->error], 422);
|
||||
}
|
||||
|
||||
return response()->json(['ok' => true, 'dry_run' => (bool) $share->dry_run, 'url' => $share->external_url], 201);
|
||||
}
|
||||
|
||||
private function back(string $notice): RedirectResponse
|
||||
{
|
||||
return redirect(route(Names::route('sharing.index'), ['notice' => $notice]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Sharing;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* Sharing posts on social networks: connect the owner's account of a platform (OAuth) and post a published post there with one
|
||||
* button. LinkedIn comes with the package; a site adds its own platforms with `manager.sharing.platforms`
|
||||
* (a class that implements `Contracts\Sharer`). Off by default.
|
||||
*/
|
||||
class SharingModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'sharing';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Sharing';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function requires(): array
|
||||
{
|
||||
return ['posts'];
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['social_connections', 'post_shares'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('sharing.view', 'See where posts are shared', 'Sharing'),
|
||||
new Permission('sharing.publish', 'Share a post on a social network', 'Sharing', needs: ['sharing.view']),
|
||||
new Permission('sharing.manage', 'Connect and disconnect the accounts of the social networks', 'Sharing', needs: ['sharing.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Sharing', 'route' => Names::route('sharing.index'), 'permission' => 'sharing.view']];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> what the settings screen can change */
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'manager.sharing.live' => ['label' => 'Post for real', 'type' => 'toggle', 'group' => 'Sharing', 'help' => 'Off: a share is written down as a dry run and nothing is sent. Keep it off on a test site.', 'env' => 'MANAGER_SHARING_LIVE'],
|
||||
'manager.sharing.post_url' => ['label' => 'Address of a post', 'type' => 'url', 'group' => 'Sharing', 'sensitive' => true, 'help' => 'Where a post lives on the site, with {slug} for its address, for example https://example.test/blog/{slug}', 'env' => 'MANAGER_SHARING_POST_URL'],
|
||||
'manager.sharing.linkedin.client_id' => ['label' => 'LinkedIn: client id', 'type' => 'text', 'group' => 'Sharing', 'sensitive' => true, 'env' => 'MANAGER_LINKEDIN_CLIENT_ID'],
|
||||
'manager.sharing.linkedin.client_secret' => ['label' => 'LinkedIn: client secret', 'type' => 'secret', 'group' => 'Sharing', 'env' => 'MANAGER_LINKEDIN_CLIENT_SECRET'],
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'sharing.connect' => ['Went to a social network to connect an account'],
|
||||
'sharing.callback' => ['Connected an account of a social network'],
|
||||
'sharing.disconnect' => ['Disconnected an account of a social network'],
|
||||
'sharing.share' => ['Shared a post on a social network'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['sharing.index' => 'Opened the sharing screen', 'sharing.post' => 'Opened how a post is shared'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?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('social_connections'), function (Blueprint $table) {
|
||||
$table->string('name', 20)->primary();
|
||||
$table->text('access_token');
|
||||
$table->dateTime('expires_at')->nullable();
|
||||
$table->text('refresh_token')->nullable();
|
||||
$table->dateTime('refresh_token_expires_at')->nullable();
|
||||
$table->string('account_id')->nullable();
|
||||
$table->string('account_name')->nullable();
|
||||
$table->json('details')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Tables::create(Names::table('post_shares'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('post_id')->index();
|
||||
$table->string('platform', 20);
|
||||
// pending, sharing, shared or failed
|
||||
$table->string('status', 10)->default('pending');
|
||||
$table->text('text')->nullable();
|
||||
$table->string('external_id')->nullable();
|
||||
$table->string('external_url', 2048)->nullable();
|
||||
$table->string('error', 500)->nullable();
|
||||
// Written down as done, but nothing was sent (the site does not post for real).
|
||||
$table->boolean('dry_run')->default(false);
|
||||
$table->dateTime('shared_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['status', 'post_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('post_shares'));
|
||||
Schema::dropIfExists(Names::table('social_connections'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Sharing\SharingController;
|
||||
|
||||
Route::prefix('/sharing')->where(['platform' => '[a-z][a-z0-9_]{0,19}'])->group(function () {
|
||||
Route::get('/', [SharingController::class, 'index'])->name('sharing.index')->middleware('can:sharing.view');
|
||||
Route::get('/{platform}/connect', [SharingController::class, 'connect'])->name('sharing.connect')->middleware('can:sharing.manage');
|
||||
Route::get('/{platform}/callback', [SharingController::class, 'callback'])->name('sharing.callback')->middleware('can:sharing.manage');
|
||||
Route::delete('/{platform}', [SharingController::class, 'disconnect'])->name('sharing.disconnect')->middleware('can:sharing.manage');
|
||||
});
|
||||
|
||||
Route::get('/posts/{post}/sharing', [SharingController::class, 'post'])->whereNumber('post')->name('sharing.post')->middleware('can:sharing.publish');
|
||||
Route::post('/posts/{post}/share', [SharingController::class, 'share'])->whereNumber('post')->name('sharing.share')->middleware('can:sharing.publish');
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\UserAgent;
|
||||
|
||||
/**
|
||||
* Counts the programs that fetch pages: search engines, AI crawlers, link
|
||||
* previews, monitors, scripts. The only code that writes to `bot_hits`.
|
||||
*
|
||||
* A program never runs the script that reports a page view, so it is seen here,
|
||||
* on the server, while the page is served (CountBots). All that is kept is a
|
||||
* counter per day, program and page: no address, no browser line, nothing that
|
||||
* could be a person. The visitor statistics themselves never hold a program.
|
||||
*/
|
||||
final class BotRecorder
|
||||
{
|
||||
/** A program without a name of its own, or one too many. */
|
||||
public const OTHER = 'Other';
|
||||
|
||||
/**
|
||||
* Names that are not in the list of UserAgent come from the request, so
|
||||
* anyone can make them up. After this many different ones in a day the rest
|
||||
* is filed under "Other": the table cannot be filled with invented names.
|
||||
*/
|
||||
public const UNKNOWN_NAMES_A_DAY = 100;
|
||||
|
||||
/** Counts one page that was served to a program. Does nothing for a person. */
|
||||
public function hit(string $userAgent, string $path): void
|
||||
{
|
||||
$table = Names::table('bot_hits');
|
||||
$bot = (new UserAgent($userAgent))->bot();
|
||||
|
||||
if ($bot === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$day = now()->toDateString();
|
||||
$name = $bot['name'] ?? self::OTHER;
|
||||
|
||||
if ($bot['kind'] === 'other' && $name !== self::OTHER && $this->isOneTooMany($table, $day, $name)) {
|
||||
$name = self::OTHER;
|
||||
}
|
||||
|
||||
// One statement, so two requests at the same moment both count.
|
||||
DB::table($table)->upsert(
|
||||
[['day' => $day, 'bot' => $name, 'kind' => $bot['kind'], 'path' => Str::limit('/'.trim(Str::before($path, '?'), '/'), 255, ''), 'hits' => 1]],
|
||||
['day', 'bot', 'path'],
|
||||
['hits' => DB::raw($table.'.hits + 1')],
|
||||
);
|
||||
}
|
||||
|
||||
private function isOneTooMany(string $table, string $day, string $name): bool
|
||||
{
|
||||
$unknown = DB::table($table)->where('day', $day)->where('kind', 'other');
|
||||
|
||||
if ((clone $unknown)->where('bot', $name)->exists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $unknown->distinct()->count('bot') >= self::UNKNOWN_NAMES_A_DAY;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Counts the public pages that are served to a program (see BotRecorder). Only a
|
||||
* page that exists and was served: an address that is made up, a redirect and the
|
||||
* manager are left out, so the list of pages cannot be filled with nonsense.
|
||||
*/
|
||||
class CountBots
|
||||
{
|
||||
public function __construct(private readonly BotRecorder $recorder) {}
|
||||
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$response = $next($request);
|
||||
|
||||
if ($this->counts($request, $response)) {
|
||||
try {
|
||||
$this->recorder->hit((string) $request->userAgent(), $request->getPathInfo());
|
||||
} catch (Throwable $e) {
|
||||
// Counting must never be the reason a page is not served.
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function counts(Request $request, Response $response): bool
|
||||
{
|
||||
$name = $request->route()?->getName();
|
||||
|
||||
return $request->isMethod('GET')
|
||||
&& $response->getStatusCode() === 200
|
||||
&& is_string($name)
|
||||
&& ! str_starts_with($name, Names::routePrefix())
|
||||
// The same promise as for visitors: who asks not to be followed is not counted at all.
|
||||
&& $request->header('Sec-GPC') !== '1'
|
||||
&& $request->header('DNT') !== '1';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Closure;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
|
||||
/**
|
||||
* Which addresses count as a page of the site. Only these are written to the statistics, so a
|
||||
* visitor (or a script) cannot fill them with made-up addresses. The default list is the config
|
||||
* (`manager.statistics.pages`, plus the posts under `manager.statistics.posts_path` when the
|
||||
* posts module is on); a site with more kinds of pages adds a resolver of its own.
|
||||
*/
|
||||
final class CountedPages
|
||||
{
|
||||
/** @var list<Closure(string): (array{path: string, post_id: int|null}|null)> */
|
||||
private array $resolvers = [];
|
||||
|
||||
/**
|
||||
* @param Closure(string): (array{path: string, post_id: int|null}|null) $resolver gets a path like `/about`, returns the page or null
|
||||
*/
|
||||
public function register(Closure $resolver): void
|
||||
{
|
||||
$this->resolvers[] = $resolver;
|
||||
}
|
||||
|
||||
/** @return array{path: string, post_id: int|null}|null */
|
||||
public function resolve(string $path): ?array
|
||||
{
|
||||
$pages = array_map(fn (string $page) => '/'.trim($page, '/'), (array) config('manager.statistics.pages', ['/']));
|
||||
|
||||
if (in_array($path, $pages, true)) {
|
||||
return ['path' => $path, 'post_id' => null];
|
||||
}
|
||||
|
||||
$postsPath = config('manager.statistics.posts_path');
|
||||
|
||||
if (is_string($postsPath) && $postsPath !== '' && Manager::enabled('posts')) {
|
||||
$prefix = '/'.trim($postsPath, '/').'/';
|
||||
|
||||
if (str_starts_with($path, $prefix)) {
|
||||
$post = Post::query()->published()->where('slug', substr($path, strlen($prefix)))->first();
|
||||
|
||||
return $post instanceof Post ? ['path' => $path, 'post_id' => $post->id] : null;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->resolvers as $resolver) {
|
||||
$page = $resolver($path);
|
||||
|
||||
if ($page !== null) {
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use IriksIT\Manager\Models\VisitorSalt;
|
||||
|
||||
class ForgetVisitorKeys extends Command
|
||||
{
|
||||
protected $signature = 'manager:forget-visitor-keys';
|
||||
|
||||
protected $description = 'Delete the keys of past days, so the visitor codes of those days can no longer be traced back';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$this->line(sprintf('%d key(s) of past days deleted.', VisitorSalt::forgetOld()));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* Where the public pages report a page view and the time spent on it. These routes run without
|
||||
* the `web` middleware: no session and no cookie, the statistics need neither.
|
||||
*/
|
||||
class PulseController
|
||||
{
|
||||
/** The script of the public pages (`<x-manager::pulse />` puts it in the page). */
|
||||
public function script(): BinaryFileResponse
|
||||
{
|
||||
return response()->file(__DIR__.'/../../../resources/js/pulse.js', [
|
||||
'Content-Type' => 'application/javascript',
|
||||
'Cache-Control' => 'public, max-age=3600',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
|
||||
public function view(Request $request, VisitRecorder $recorder): JsonResponse
|
||||
{
|
||||
// A browser that says its user does not want to be followed is not counted at all.
|
||||
if ($request->header('Sec-GPC') === '1' || $request->header('DNT') === '1') {
|
||||
return response()->json(['token' => null])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
$countryHeader = config('manager.statistics.country_header');
|
||||
|
||||
$token = $recorder->view(
|
||||
(string) $request->ip(),
|
||||
(string) $request->userAgent(),
|
||||
$request->string('path')->limit(300, '')->toString(),
|
||||
[
|
||||
'via' => $request->string('via')->limit(40, '')->toString(),
|
||||
'campaign' => $request->string('campaign')->limit(80, '')->toString(),
|
||||
'referrer' => $request->string('referrer')->limit(2000, '')->toString(),
|
||||
// Only the country code is kept, and only when the site names the header that has it (Cloudflare: CF-IPCountry).
|
||||
'country' => is_string($countryHeader) && $countryHeader !== '' ? (string) $request->header($countryHeader, '') : '',
|
||||
'host' => $request->getHost(),
|
||||
],
|
||||
);
|
||||
|
||||
return response()->json(['token' => $token])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
public function leave(Request $request, VisitRecorder $recorder): Response
|
||||
{
|
||||
$recorder->leave($request->string('token')->limit(40, '')->toString(), $request->integer('seconds'));
|
||||
|
||||
return response()->noContent()->header('Cache-Control', 'no-store');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
/**
|
||||
* Where a visit came from: the channel (direct, search, social, referral, share,
|
||||
* campaign), the platform or site behind it, and the host of the page that
|
||||
* linked here.
|
||||
*
|
||||
* "share" is a link the site posted itself: those carry ?via=<platform>, which
|
||||
* is what tells a click on my own post apart from someone else's link.
|
||||
*/
|
||||
final class Source
|
||||
{
|
||||
/** The platforms the site shares posts to; the values of ?via=. */
|
||||
public const PLATFORMS = ['linkedin', 'x', 'facebook', 'instagram'];
|
||||
|
||||
/** Host (or the end of one) => platform. */
|
||||
private const SOCIAL = [
|
||||
'linkedin.com' => 'linkedin', 'lnkd.in' => 'linkedin', 'com.linkedin.android' => 'linkedin',
|
||||
't.co' => 'x', 'x.com' => 'x', 'twitter.com' => 'x', 'com.twitter.android' => 'x',
|
||||
'facebook.com' => 'facebook', 'fb.com' => 'facebook', 'fb.me' => 'facebook', 'com.facebook.katana' => 'facebook',
|
||||
'instagram.com' => 'instagram', 'com.instagram.android' => 'instagram',
|
||||
'threads.net' => 'threads', 'threads.com' => 'threads', 'bsky.app' => 'bluesky', 'reddit.com' => 'reddit',
|
||||
'youtube.com' => 'youtube', 'youtu.be' => 'youtube', 'news.ycombinator.com' => 'hackernews',
|
||||
'tweakers.net' => 'tweakers',
|
||||
];
|
||||
|
||||
/** Host (or the end of one) => search engine. */
|
||||
private const SEARCH = [
|
||||
'bing.com' => 'bing', 'duckduckgo.com' => 'duckduckgo', 'ecosia.org' => 'ecosia',
|
||||
'startpage.com' => 'startpage', 'search.brave.com' => 'brave', 'yandex.com' => 'yandex', 'yandex.ru' => 'yandex',
|
||||
'baidu.com' => 'baidu', 'kagi.com' => 'kagi', 'qwant.com' => 'qwant', 'search.yahoo.com' => 'yahoo',
|
||||
'com.google.android.googlequicksearchbox' => 'google',
|
||||
];
|
||||
|
||||
private function __construct(
|
||||
public readonly string $channel,
|
||||
public readonly ?string $source,
|
||||
public readonly ?string $referrerHost,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param string $via the ?via= of the address the visitor arrived on
|
||||
* @param string $campaign its ?utm_source=
|
||||
* @param string $referrer the address of the page that linked here
|
||||
* @param string $ownHost this site's own host: a link from the site itself is no source
|
||||
*/
|
||||
public static function of(string $via, string $campaign, string $referrer, string $ownHost): self
|
||||
{
|
||||
$host = self::host($referrer);
|
||||
if ($host === self::bare($ownHost)) {
|
||||
$host = null;
|
||||
}
|
||||
|
||||
$via = strtolower(trim($via));
|
||||
if (in_array($via, self::PLATFORMS, true)) {
|
||||
return new self('share', $via, $host);
|
||||
}
|
||||
|
||||
$campaign = strtolower(trim($campaign));
|
||||
if ($campaign !== '' && preg_match('/^[a-z0-9._-]{1,80}$/', $campaign) === 1) {
|
||||
$platform = self::SOCIAL[$campaign.'.com'] ?? ($campaign === 'twitter' ? 'x' : null);
|
||||
|
||||
return $platform !== null ? new self('social', $platform, $host) : new self('campaign', $campaign, $host);
|
||||
}
|
||||
|
||||
if ($host === null) {
|
||||
return new self('direct', null, null);
|
||||
}
|
||||
|
||||
if (($platform = self::match($host, self::SOCIAL)) !== null) {
|
||||
return new self('social', $platform, $host);
|
||||
}
|
||||
|
||||
// google.com, google.nl, google.co.uk ...
|
||||
if (preg_match('/(^|\.)google\.[a-z.]{2,6}$/', $host) === 1) {
|
||||
return new self('search', 'google', $host);
|
||||
}
|
||||
|
||||
if (($engine = self::match($host, self::SEARCH)) !== null) {
|
||||
return new self('search', $engine, $host);
|
||||
}
|
||||
|
||||
return new self('referral', $host, $host);
|
||||
}
|
||||
|
||||
/** The host of an address, lower case and without "www."; null when there is none. */
|
||||
private static function host(string $address): ?string
|
||||
{
|
||||
$address = trim($address);
|
||||
if ($address === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$host = parse_url($address, PHP_URL_HOST);
|
||||
if (! is_string($host) || $host === '' || strlen($host) > 255) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::bare($host);
|
||||
}
|
||||
|
||||
private static function bare(string $host): string
|
||||
{
|
||||
$host = strtolower($host);
|
||||
|
||||
return str_starts_with($host, 'www.') ? substr($host, 4) : $host;
|
||||
}
|
||||
|
||||
/** @param array<string, string> $known */
|
||||
private static function match(string $host, array $known): ?string
|
||||
{
|
||||
foreach ($known as $end => $name) {
|
||||
if ($host === $end || str_ends_with($host, '.'.$end)) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,746 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* The numbers of the visitor statistics, for the manager. The only code that
|
||||
* reads `visits`, `page_views` and `bot_hits` for a report.
|
||||
*
|
||||
* The database only ever groups by the plain `day`, `hour` and `weekday`
|
||||
* columns; weeks, months and years are added up here. That keeps every query the
|
||||
* same on MySQL and on SQLite (the tests).
|
||||
*
|
||||
* "Visitors" are counted per day: the visitor code changes at midnight, so
|
||||
* someone who comes back the next day is a new visitor.
|
||||
*/
|
||||
final class Statistics
|
||||
{
|
||||
/** The periods the manager offers, next to one per year (as "2026"). */
|
||||
public const RANGES = [
|
||||
'today' => 'Today', 'week' => 'This week', '7d' => 'Last 7 days', 'month' => 'This month', '30d' => 'Last 30 days',
|
||||
'12m' => 'Last 12 months', 'all' => 'All time',
|
||||
];
|
||||
|
||||
/** A period between two dates of one's own choosing (`from` and `to`). */
|
||||
public const CUSTOM = 'custom';
|
||||
|
||||
/** What a period can be put next to: the one before it, the same days a year earlier, days of one's own choosing, or nothing. */
|
||||
public const COMPARISONS = ['previous' => 'The period before', 'year' => 'A year earlier', 'custom' => 'Another period', 'none' => 'Nothing'];
|
||||
|
||||
/** What can be downloaded as a CSV file. */
|
||||
public const EXPORTS = ['days' => 'Per day', 'pages' => 'Pages', 'sources' => 'Sources', 'bots' => 'Bots'];
|
||||
|
||||
public const DEFAULT_RANGE = '30d';
|
||||
|
||||
private const WEEKDAYS = [1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', 7 => 'Sun'];
|
||||
|
||||
/**
|
||||
* Everything the statistics page shows for one period.
|
||||
*
|
||||
* @param array<string, string> $choice `from` and `to` for a period of one's own, `compare` (see COMPARISONS) and `compare_from`
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function report(string $range, array $choice = []): array
|
||||
{
|
||||
$period = $this->period($range, $choice);
|
||||
$from = $period['from'];
|
||||
$to = $period['to'];
|
||||
$compares = $period['previous_from'] !== null && $period['previous_to'] !== null;
|
||||
|
||||
return [
|
||||
'range' => [
|
||||
'key' => $period['key'],
|
||||
'label' => $period['label'],
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'bucket' => $period['bucket'],
|
||||
'compare' => $period['compare'],
|
||||
'compared_to' => $period['compared_to'],
|
||||
'previous_from' => $period['previous_from'],
|
||||
'previous_to' => $period['previous_to'],
|
||||
],
|
||||
'ranges' => $this->ranges(),
|
||||
'comparisons' => self::COMPARISONS,
|
||||
'exports' => self::EXPORTS,
|
||||
'totals' => $this->totals($from, $to),
|
||||
'previous' => $compares ? $this->totals((string) $period['previous_from'], (string) $period['previous_to'], $period['previous_until_hour']) : null,
|
||||
'series' => $this->series($from, $to, $period['bucket']),
|
||||
// The other period, step by step: the first step of it next to the first step of this one.
|
||||
'previous_series' => $compares ? $this->series((string) $period['previous_from'], (string) $period['previous_to'], $period['bucket']) : null,
|
||||
'pages' => $this->pages($from, $to),
|
||||
'posts' => $this->posts($from, $to),
|
||||
'channels' => $this->grouped($from, $to, 'channel', 10),
|
||||
'platforms' => $this->platforms($from, $to),
|
||||
'sources' => $this->sources($from, $to),
|
||||
'heatmap' => $this->heatmap($from, $to),
|
||||
'countries' => $this->grouped($from, $to, 'country', 8),
|
||||
'devices' => $this->grouped($from, $to, 'device', 5),
|
||||
'browsers' => $this->grouped($from, $to, 'browser', 6),
|
||||
'systems' => $this->grouped($from, $to, 'os', 6),
|
||||
// Programs have no hour, so "today until now" has nothing fair to stand next to.
|
||||
'bots' => $this->bots($from, $to, $compares && $period['previous_until_hour'] === null ? [(string) $period['previous_from'], (string) $period['previous_to']] : null),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The few numbers of a period that the screen of the owner shows (`OwnerNumbers`): the
|
||||
* totals next to the period before, the visitors step by step, and the pages, articles
|
||||
* and ways in that were used most.
|
||||
*
|
||||
* @return array{from: string, to: string, bucket: string, totals: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}, previous: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}|null, series: list<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>, pages: list<array{path: string, title: string|null, views: int, average_seconds: int}>, posts: list<array{title: string, slug: string, views: int, average_seconds: int}>, channels: list<array{name: string, visits: int}>}
|
||||
*/
|
||||
public function brief(string $range): array
|
||||
{
|
||||
$period = $this->period($range);
|
||||
$from = $period['from'];
|
||||
$to = $period['to'];
|
||||
|
||||
return [
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'bucket' => $period['bucket'],
|
||||
'totals' => $this->totals($from, $to),
|
||||
'previous' => $period['previous_from'] !== null && $period['previous_to'] !== null
|
||||
? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour'])
|
||||
: null,
|
||||
'series' => $this->series($from, $to, $period['bucket']),
|
||||
'pages' => $this->pages($from, $to, 6),
|
||||
'posts' => $this->posts($from, $to),
|
||||
'channels' => $this->grouped($from, $to, 'channel', 6),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* One list of the period as rows for a CSV file. An unknown list gives the days.
|
||||
*
|
||||
* @param array<string, string> $choice
|
||||
* @return array{filename: string, header: list<string>, rows: list<list<string|int>>}
|
||||
*/
|
||||
public function export(string $sheet, string $range, array $choice = []): array
|
||||
{
|
||||
$period = $this->period($range, $choice);
|
||||
$from = $period['from'];
|
||||
$to = $period['to'];
|
||||
$sheet = array_key_exists($sheet, self::EXPORTS) ? $sheet : 'days';
|
||||
|
||||
[$header, $rows] = match ($sheet) {
|
||||
'pages' => [['Page', 'Title', 'Views', 'Average seconds on the page'], array_map(
|
||||
fn (array $page) => [$page['path'], $page['title'] ?? '', $page['views'], $page['average_seconds']],
|
||||
$this->pages($from, $to, null),
|
||||
)],
|
||||
'sources' => [['Source', 'Channel', 'Visits'], array_map(
|
||||
fn (array $source) => [$source['name'], $source['channel'], $source['visits']],
|
||||
$this->sources($from, $to, null),
|
||||
)],
|
||||
'bots' => [['Program', 'Kind', 'Page', 'Requests'], $this->botRows($from, $to)],
|
||||
default => [['Day', 'Visitors', 'Visits', 'Page views', 'Requests by programs'], array_map(
|
||||
fn (array $day) => [$day['key'], $day['visitors'], $day['visits'], $day['page_views'], $day['bot_hits']],
|
||||
$this->series($from, $to, 'day'),
|
||||
)],
|
||||
};
|
||||
|
||||
return ['filename' => "statistics-{$sheet}-{$from}-to-{$to}.csv", 'header' => $header, 'rows' => $rows];
|
||||
}
|
||||
|
||||
/**
|
||||
* The short version for the dashboard: today, the last 7 and the last 30 days,
|
||||
* each next to the period before it, and the visitors per day of the last 30 days.
|
||||
*
|
||||
* @return array{periods: list<array{key: string, label: string, visitors: int, page_views: int, previous_visitors: int}>, days: list<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>}
|
||||
*/
|
||||
public function summary(): array
|
||||
{
|
||||
$periods = [];
|
||||
|
||||
foreach (['today', '7d', '30d'] as $range) {
|
||||
$period = $this->period($range);
|
||||
$now = $this->totals($period['from'], $period['to']);
|
||||
$before = $period['previous_from'] !== null && $period['previous_to'] !== null
|
||||
? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour'])
|
||||
: null;
|
||||
|
||||
$periods[] = [
|
||||
'key' => $range,
|
||||
'label' => $period['label'],
|
||||
'visitors' => $now['visitors'],
|
||||
'page_views' => $now['page_views'],
|
||||
'previous_visitors' => $before['visitors'] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
$month = $this->period('30d');
|
||||
|
||||
return ['periods' => $periods, 'days' => $this->series($month['from'], $month['to'], 'day')];
|
||||
}
|
||||
|
||||
/**
|
||||
* A period as dates, with the period it is compared with. An unknown key
|
||||
* gives the default period.
|
||||
*
|
||||
* @param array<string, string> $choice
|
||||
* @return array{key: string, label: string, from: string, to: string, bucket: string, compare: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null}
|
||||
*/
|
||||
private function period(string $range, array $choice = []): array
|
||||
{
|
||||
$period = $this->dates($range, $choice);
|
||||
$compare = $choice['compare'] ?? 'previous';
|
||||
$nothing = ['compare' => 'none', 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, 'previous_until_hour' => null];
|
||||
|
||||
// All time has nothing before it.
|
||||
if ($period['previous_from'] === null || $compare === 'none') {
|
||||
return $nothing + $period;
|
||||
}
|
||||
|
||||
$from = CarbonImmutable::parse($period['from']);
|
||||
$to = CarbonImmutable::parse($period['to']);
|
||||
|
||||
if ($compare === 'year') {
|
||||
return [
|
||||
'compare' => 'year', 'compared_to' => 'the same days a year earlier',
|
||||
'previous_from' => $from->subYearNoOverflow()->toDateString(), 'previous_to' => $to->subYearNoOverflow()->toDateString(),
|
||||
] + $period;
|
||||
}
|
||||
|
||||
$start = $compare === 'custom' ? self::date($choice['compare_from'] ?? '') : null;
|
||||
|
||||
if ($start !== null) {
|
||||
// As many days as the period itself, from the chosen day on.
|
||||
$end = $start->addDays((int) $from->diffInDays($to));
|
||||
|
||||
return [
|
||||
'compare' => 'custom', 'compared_to' => self::span($start, $end),
|
||||
'previous_from' => $start->toDateString(), 'previous_to' => $end->toDateString(),
|
||||
] + $period;
|
||||
}
|
||||
|
||||
return ['compare' => 'previous'] + $period;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dates of a period, and of the period before it.
|
||||
*
|
||||
* @param array<string, string> $choice
|
||||
* @return array{key: string, label: string, from: string, to: string, bucket: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null}
|
||||
*/
|
||||
private function dates(string $range, array $choice): array
|
||||
{
|
||||
$today = CarbonImmutable::now()->startOfDay();
|
||||
$day = fn (CarbonImmutable $date): string => $date->toDateString();
|
||||
|
||||
if (preg_match('/^\d{4}$/', $range) === 1 && in_array((int) $range, $this->years(), true)) {
|
||||
$start = $today->setDate((int) $range, 1, 1);
|
||||
|
||||
return [
|
||||
'key' => $range, 'label' => $range, 'from' => $day($start), 'to' => $day($start->endOfYear()), 'bucket' => 'month',
|
||||
'compared_to' => (string) ((int) $range - 1),
|
||||
'previous_from' => $day($start->subYear()), 'previous_to' => $day($start->subDay()), 'previous_until_hour' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$from = self::date($choice['from'] ?? '');
|
||||
$to = self::date($choice['to'] ?? '');
|
||||
|
||||
if ($range === self::CUSTOM && $from !== null && $to !== null) {
|
||||
// The wrong way round, or into the future: still a period.
|
||||
[$from, $to] = $from <= $to ? [$from, $to] : [$to, $from];
|
||||
$to = $to->min($today);
|
||||
$from = $from->min($to);
|
||||
$days = (int) $from->diffInDays($to) + 1;
|
||||
|
||||
return [
|
||||
'key' => self::CUSTOM, 'label' => self::span($from, $to), 'from' => $day($from), 'to' => $day($to),
|
||||
'bucket' => match (true) {
|
||||
$days === 1 => 'hour',
|
||||
$days <= 92 => 'day',
|
||||
$days <= 1100 => 'month',
|
||||
default => 'year',
|
||||
},
|
||||
'compared_to' => $days === 1 ? 'the day before' : "the {$days} days before",
|
||||
'previous_from' => $day($from->subDays($days)), 'previous_to' => $day($from->subDay()), 'previous_until_hour' => null,
|
||||
];
|
||||
}
|
||||
|
||||
if (! array_key_exists($range, self::RANGES)) {
|
||||
$range = self::DEFAULT_RANGE;
|
||||
}
|
||||
|
||||
$period = ['key' => $range, 'label' => self::RANGES[$range], 'to' => $day($today), 'previous_until_hour' => null];
|
||||
$monday = $today->startOfWeek(CarbonImmutable::MONDAY);
|
||||
$lastMonth = $today->startOfMonth()->subMonthNoOverflow();
|
||||
|
||||
return match ($range) {
|
||||
// Today so far, next to yesterday up to the same hour: a fair comparison at any time of day.
|
||||
'today' => ['previous_until_hour' => CarbonImmutable::now()->hour] + $period + [
|
||||
'from' => $day($today), 'bucket' => 'hour', 'compared_to' => 'yesterday at this time',
|
||||
'previous_from' => $day($today->subDay()), 'previous_to' => $day($today->subDay()),
|
||||
],
|
||||
// A week and a month that are still running stand next to as many days of the one before.
|
||||
'week' => $period + [
|
||||
'from' => $day($monday), 'bucket' => 'day', 'compared_to' => 'last week up to the same day',
|
||||
'previous_from' => $day($monday->subWeek()), 'previous_to' => $day($today->subWeek()),
|
||||
],
|
||||
'month' => $period + [
|
||||
'from' => $day($today->startOfMonth()), 'bucket' => 'day', 'compared_to' => 'last month up to the same day',
|
||||
'previous_from' => $day($lastMonth), 'previous_to' => $day($lastMonth->setDay(min($today->day, $lastMonth->daysInMonth))),
|
||||
],
|
||||
'7d' => $period + [
|
||||
'from' => $day($today->subDays(6)), 'bucket' => 'day', 'compared_to' => 'the 7 days before',
|
||||
'previous_from' => $day($today->subDays(13)), 'previous_to' => $day($today->subDays(7)),
|
||||
],
|
||||
'12m' => $period + [
|
||||
'from' => $day($today->startOfMonth()->subMonthsNoOverflow(11)), 'bucket' => 'month', 'compared_to' => 'the 12 months before',
|
||||
'previous_from' => $day($today->startOfMonth()->subMonthsNoOverflow(23)),
|
||||
'previous_to' => $day($today->startOfMonth()->subMonthsNoOverflow(11)->subDay()),
|
||||
],
|
||||
'all' => $period + [
|
||||
'from' => $this->firstDay() ?? $day($today),
|
||||
// Months while that still fits on the screen, years after that.
|
||||
'bucket' => CarbonImmutable::parse($this->firstDay() ?? $day($today))->diffInMonths($today) > 24 ? 'year' : 'month',
|
||||
'compared_to' => null, 'previous_from' => null, 'previous_to' => null,
|
||||
],
|
||||
default => $period + [
|
||||
'from' => $day($today->subDays(29)), 'bucket' => 'day', 'compared_to' => 'the 30 days before',
|
||||
'previous_from' => $day($today->subDays(59)), 'previous_to' => $day($today->subDays(30)),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** A date as 'Y-m-d' from the address bar, or null when it is not one. */
|
||||
private static function date(string $value): ?CarbonImmutable
|
||||
{
|
||||
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value);
|
||||
|
||||
// "2026-02-31" is read as the 3rd of March: not what was typed, so not a date.
|
||||
return $date instanceof CarbonImmutable && $date->toDateString() === $value && $date->year >= 2000 ? $date : null;
|
||||
}
|
||||
|
||||
/** "1 Oct – 31 Oct 2026" */
|
||||
private static function span(CarbonImmutable $from, CarbonImmutable $to): string
|
||||
{
|
||||
if ($from->equalTo($to)) {
|
||||
return $from->format('j M Y');
|
||||
}
|
||||
|
||||
return $from->format($from->year === $to->year ? 'j M' : 'j M Y').' – '.$to->format('j M Y');
|
||||
}
|
||||
|
||||
/**
|
||||
* The periods to choose from: the fixed ones and every year there are visits of.
|
||||
*
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
private function ranges(): array
|
||||
{
|
||||
$ranges = [];
|
||||
foreach (self::RANGES as $key => $label) {
|
||||
$ranges[] = ['key' => $key, 'label' => $label];
|
||||
}
|
||||
foreach (array_reverse($this->years()) as $year) {
|
||||
$ranges[] = ['key' => (string) $year, 'label' => (string) $year];
|
||||
}
|
||||
|
||||
return $ranges;
|
||||
}
|
||||
|
||||
/** @return list<int> every year from the first visit until now */
|
||||
private function years(): array
|
||||
{
|
||||
$first = $this->firstDay();
|
||||
|
||||
return $first === null ? [] : range((int) substr($first, 0, 4), CarbonImmutable::now()->year);
|
||||
}
|
||||
|
||||
private function firstDay(): ?string
|
||||
{
|
||||
$first = DB::table($this->table('visits'))->min('day');
|
||||
|
||||
return is_string($first) ? substr($first, 0, 10) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|null $untilHour only count visits that started in or before this hour of the day
|
||||
* @return array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}
|
||||
*/
|
||||
private function totals(string $from, string $to, ?int $untilHour = null): array
|
||||
{
|
||||
$row = $this->visits($from, $to)
|
||||
->when($untilHour !== null, fn (Builder $query) => $query->where('hour', '<=', $untilHour))
|
||||
->selectRaw('count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views')
|
||||
->selectRaw('sum(seconds) as seconds, sum(case when page_views <= 1 then 1 else 0 end) as bounces')
|
||||
->first();
|
||||
|
||||
$visits = self::number($row->visits ?? 0);
|
||||
|
||||
return [
|
||||
'visitors' => self::number($row->visitors ?? 0),
|
||||
'visits' => $visits,
|
||||
'page_views' => self::number($row->page_views ?? 0),
|
||||
'average_seconds' => $visits > 0 ? (int) round(self::number($row->seconds ?? 0) / $visits) : 0,
|
||||
// Visits that ended after a single page, as a percentage.
|
||||
'bounce_rate' => $visits > 0 ? (int) round(100 * self::number($row->bounces ?? 0) / $visits) : 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Visitors, visits and page views through time, one entry per hour, day, month
|
||||
* or year. Every step of the period is there, also the ones without visits.
|
||||
*
|
||||
* `bot_hits` are the requests by programs; those have no hour, so per hour it stays 0.
|
||||
*
|
||||
* @return list<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>
|
||||
*/
|
||||
private function series(string $from, string $to, string $bucket): array
|
||||
{
|
||||
$column = $bucket === 'hour' ? 'hour' : 'day';
|
||||
$rows = $this->visits($from, $to)
|
||||
->selectRaw("{$column} as step, count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views")
|
||||
->groupBy($column)
|
||||
->get();
|
||||
|
||||
$steps = [];
|
||||
$start = CarbonImmutable::parse($from);
|
||||
$end = CarbonImmutable::parse($to);
|
||||
|
||||
if ($bucket === 'hour') {
|
||||
foreach (range(0, 23) as $hour) {
|
||||
$steps[(string) $hour] = sprintf('%02d:00', $hour);
|
||||
}
|
||||
} elseif ($bucket === 'day') {
|
||||
for ($date = $start; $date <= $end; $date = $date->addDay()) {
|
||||
$steps[$date->toDateString()] = $date->format('j M');
|
||||
}
|
||||
} elseif ($bucket === 'month') {
|
||||
for ($date = $start->startOfMonth(); $date <= $end; $date = $date->addMonth()) {
|
||||
$steps[$date->format('Y-m')] = $date->format('M Y');
|
||||
}
|
||||
} else {
|
||||
foreach (range($start->year, $end->year) as $year) {
|
||||
$steps[(string) $year] = (string) $year;
|
||||
}
|
||||
}
|
||||
|
||||
$series = [];
|
||||
foreach ($steps as $key => $label) {
|
||||
$series[(string) $key] = ['key' => (string) $key, 'label' => $label, 'visitors' => 0, 'visits' => 0, 'page_views' => 0, 'bot_hits' => 0];
|
||||
}
|
||||
|
||||
$keyOf = fn (mixed $step): string => match ($bucket) {
|
||||
'hour' => (string) (int) (is_scalar($step) ? $step : 0),
|
||||
'day' => substr(is_scalar($step) ? (string) $step : '', 0, 10),
|
||||
'month' => substr(is_scalar($step) ? (string) $step : '', 0, 7),
|
||||
default => substr(is_scalar($step) ? (string) $step : '', 0, 4),
|
||||
};
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$key = $keyOf($row->step);
|
||||
|
||||
if (isset($series[$key])) {
|
||||
$series[$key]['visitors'] += self::number($row->visitors);
|
||||
$series[$key]['visits'] += self::number($row->visits);
|
||||
$series[$key]['page_views'] += self::number($row->page_views);
|
||||
}
|
||||
}
|
||||
|
||||
if ($bucket !== 'hour') {
|
||||
foreach ($this->botHits($from, $to)->selectRaw('day as step, sum(hits) as hits')->groupBy('day')->get() as $row) {
|
||||
$key = $keyOf($row->step);
|
||||
|
||||
if (isset($series[$key])) {
|
||||
$series[$key]['bot_hits'] += self::number($row->hits);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($series);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pages that were looked at most, with the average time on the page.
|
||||
*
|
||||
* @return list<array{path: string, title: string|null, views: int, average_seconds: int}>
|
||||
*/
|
||||
private function pages(string $from, string $to, ?int $limit = 10): array
|
||||
{
|
||||
$rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to])
|
||||
->selectRaw('path, max(post_id) as post_id, count(*) as views, sum(seconds) as seconds')
|
||||
->groupBy('path')->orderByDesc('views')->orderBy('path')
|
||||
->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get();
|
||||
|
||||
$titles = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->filter()->all())->pluck('title', 'id') : collect();
|
||||
|
||||
$pages = [];
|
||||
foreach ($rows as $row) {
|
||||
$views = self::number($row->views);
|
||||
$title = $titles->get(self::number($row->post_id));
|
||||
|
||||
$pages[] = [
|
||||
'path' => is_string($row->path) ? $row->path : '',
|
||||
'title' => is_string($title) ? $title : null,
|
||||
'views' => $views,
|
||||
'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0,
|
||||
];
|
||||
}
|
||||
|
||||
return $pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* The posts that were read most.
|
||||
*
|
||||
* @return list<array{title: string, slug: string, views: int, average_seconds: int}>
|
||||
*/
|
||||
private function posts(string $from, string $to): array
|
||||
{
|
||||
$rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to])->whereNotNull('post_id')
|
||||
->selectRaw('post_id, count(*) as views, sum(seconds) as seconds')
|
||||
->groupBy('post_id')->orderByDesc('views')->limit(10)->get();
|
||||
|
||||
$found = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->all())->get()->keyBy('id') : collect();
|
||||
|
||||
$posts = [];
|
||||
foreach ($rows as $row) {
|
||||
$post = $found->get(self::number($row->post_id));
|
||||
$views = self::number($row->views);
|
||||
|
||||
if ($post instanceof Post) {
|
||||
$posts[] = [
|
||||
'title' => $post->title,
|
||||
'slug' => $post->slug,
|
||||
'views' => $views,
|
||||
'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits counted by one column of `visits`, most first.
|
||||
*
|
||||
* @return list<array{name: string, visits: int}>
|
||||
*/
|
||||
private function grouped(string $from, string $to, string $column, int $limit): array
|
||||
{
|
||||
$rows = $this->visits($from, $to)->whereNotNull($column)
|
||||
->select("{$column} as name")->selectRaw('count(*) as visits')
|
||||
->groupBy($column)->orderByDesc('visits')->orderBy($column)->limit($limit)->get();
|
||||
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$result[] = ['name' => is_scalar($row->name) ? (string) $row->name : '', 'visits' => self::number($row->visits)];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The four platforms the site shares posts to: how many visits came from each,
|
||||
* and how many of those through a link the site posted itself.
|
||||
*
|
||||
* @return list<array{name: string, visits: int, shared: int}>
|
||||
*/
|
||||
private function platforms(string $from, string $to): array
|
||||
{
|
||||
$rows = $this->visits($from, $to)->whereIn('source', Source::PLATFORMS)->whereIn('channel', ['share', 'social'])
|
||||
->selectRaw('source, channel, count(*) as visits')->groupBy('source', 'channel')->get();
|
||||
|
||||
$platforms = [];
|
||||
foreach (Source::PLATFORMS as $platform) {
|
||||
$platforms[$platform] = ['name' => $platform, 'visits' => 0, 'shared' => 0];
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$name = is_string($row->source) ? $row->source : '';
|
||||
if (isset($platforms[$name])) {
|
||||
$platforms[$name]['visits'] += self::number($row->visits);
|
||||
$platforms[$name]['shared'] += $row->channel === 'share' ? self::number($row->visits) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($platforms);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sites, search engines and platforms that sent visitors, most first.
|
||||
*
|
||||
* @return list<array{name: string, channel: string, visits: int}>
|
||||
*/
|
||||
private function sources(string $from, string $to, ?int $limit = 12): array
|
||||
{
|
||||
$rows = $this->visits($from, $to)->whereNotNull('source')
|
||||
->selectRaw('source, channel, count(*) as visits')
|
||||
->groupBy('source', 'channel')->orderByDesc('visits')->orderBy('source')
|
||||
->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get();
|
||||
|
||||
$sources = [];
|
||||
foreach ($rows as $row) {
|
||||
$sources[] = [
|
||||
'name' => is_string($row->source) ? $row->source : '',
|
||||
'channel' => is_string($row->channel) ? $row->channel : '',
|
||||
'visits' => self::number($row->visits),
|
||||
];
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* The busy moments: visits per weekday and hour of the day.
|
||||
*
|
||||
* @return list<array{day: string, hours: list<int>}>
|
||||
*/
|
||||
private function heatmap(string $from, string $to): array
|
||||
{
|
||||
$rows = $this->visits($from, $to)->selectRaw('weekday, hour, count(*) as visits')->groupBy('weekday', 'hour')->get();
|
||||
|
||||
$grid = [];
|
||||
foreach (self::WEEKDAYS as $number => $name) {
|
||||
$grid[$number] = ['day' => $name, 'hours' => array_fill(0, 24, 0)];
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$weekday = self::number($row->weekday);
|
||||
$hour = self::number($row->hour);
|
||||
if (isset($grid[$weekday]) && $hour >= 0 && $hour <= 23) {
|
||||
$grid[$weekday]['hours'][$hour] = self::number($row->visits);
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($grid);
|
||||
}
|
||||
|
||||
/**
|
||||
* The programs that fetched pages (search engines, AI crawlers, link previews,
|
||||
* scripts ...): how often in all, which ones, what kind, and which pages.
|
||||
* They are counted on the server (BotRecorder) and are never part of the
|
||||
* visitors above.
|
||||
*
|
||||
* @param array{0: string, 1: string}|null $before the period to compare the total with
|
||||
* @return array{total: int, previous: int|null, names: list<array{name: string, kind: string, hits: int}>, kinds: list<array{name: string, hits: int}>, pages: list<array{path: string, hits: int}>}
|
||||
*/
|
||||
private function bots(string $from, string $to, ?array $before): array
|
||||
{
|
||||
$names = [];
|
||||
foreach ($this->botHits($from, $to)->selectRaw('bot, kind, sum(hits) as hits')
|
||||
->groupBy('bot', 'kind')->orderByDesc('hits')->orderBy('bot')->limit(15)->get() as $row) {
|
||||
$names[] = ['name' => is_string($row->bot) ? $row->bot : '', 'kind' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)];
|
||||
}
|
||||
|
||||
$kinds = [];
|
||||
foreach ($this->botHits($from, $to)->selectRaw('kind, sum(hits) as hits')
|
||||
->groupBy('kind')->orderByDesc('hits')->orderBy('kind')->get() as $row) {
|
||||
$kinds[] = ['name' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)];
|
||||
}
|
||||
|
||||
$pages = [];
|
||||
foreach ($this->botHits($from, $to)->selectRaw('path, sum(hits) as hits')
|
||||
->groupBy('path')->orderByDesc('hits')->orderBy('path')->limit(10)->get() as $row) {
|
||||
$pages[] = ['path' => is_string($row->path) ? $row->path : '', 'hits' => self::number($row->hits)];
|
||||
}
|
||||
|
||||
return [
|
||||
'total' => self::number($this->botHits($from, $to)->sum('hits')),
|
||||
'previous' => $before === null ? null : self::number($this->botHits($before[0], $before[1])->sum('hits')),
|
||||
'names' => $names,
|
||||
'kinds' => $kinds,
|
||||
'pages' => $pages,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Every program and page of the period, for the export.
|
||||
*
|
||||
* @return list<list<string|int>>
|
||||
*/
|
||||
private function botRows(string $from, string $to): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach ($this->botHits($from, $to)->selectRaw('bot, kind, path, sum(hits) as hits')
|
||||
->groupBy('bot', 'kind', 'path')->orderByDesc('hits')->orderBy('bot')->orderBy('path')->get() as $row) {
|
||||
$rows[] = [is_string($row->bot) ? $row->bot : '', is_string($row->kind) ? $row->kind : '', is_string($row->path) ? $row->path : '', self::number($row->hits)];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* How often each post was opened, since the beginning, and how those readers
|
||||
* got to it. Someone who landed on the post is counted under the way they
|
||||
* arrived (a shared post on LinkedIn, Google, direct ...); someone who was on
|
||||
* another page of the site first and clicked through is counted as "internal".
|
||||
*
|
||||
* @param int|null $postId only this post
|
||||
* @return array<int, array{views: int, average_seconds: int, sources: list<array{channel: string, name: string|null, views: int}>}> by post id
|
||||
*/
|
||||
public function readers(?int $postId = null): array
|
||||
{
|
||||
$views = $this->table('page_views');
|
||||
$visits = $this->table('visits');
|
||||
$rows = DB::table($views)
|
||||
->join($visits, "{$visits}.id", '=', "{$views}.visit_id")
|
||||
->whereNotNull("{$views}.post_id")
|
||||
->when($postId !== null, fn (Builder $query) => $query->where("{$views}.post_id", $postId))
|
||||
->selectRaw("{$views}.post_id as post, case when {$visits}.entry_path = {$views}.path then {$visits}.channel else 'internal' end as arrived_by")
|
||||
->selectRaw("case when {$visits}.entry_path = {$views}.path then {$visits}.source else null end as arrived_from")
|
||||
->selectRaw("count(*) as views, sum({$views}.seconds) as seconds")
|
||||
->groupBy('post', 'arrived_by', 'arrived_from')
|
||||
->orderByDesc('views')->orderBy('arrived_by')->orderBy('arrived_from')
|
||||
->get();
|
||||
|
||||
$posts = [];
|
||||
$seconds = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$id = self::number($row->post);
|
||||
$views = self::number($row->views);
|
||||
|
||||
$posts[$id] ??= ['views' => 0, 'average_seconds' => 0, 'sources' => []];
|
||||
$posts[$id]['views'] += $views;
|
||||
$posts[$id]['sources'][] = [
|
||||
'channel' => is_string($row->arrived_by) ? $row->arrived_by : '',
|
||||
'name' => is_string($row->arrived_from) ? $row->arrived_from : null,
|
||||
'views' => $views,
|
||||
];
|
||||
$seconds[$id] = ($seconds[$id] ?? 0) + self::number($row->seconds);
|
||||
}
|
||||
|
||||
foreach ($posts as $id => $post) {
|
||||
$posts[$id]['average_seconds'] = $post['views'] > 0 ? (int) round(($seconds[$id] ?? 0) / $post['views']) : 0;
|
||||
}
|
||||
|
||||
return $posts;
|
||||
}
|
||||
|
||||
private function visits(string $from, string $to): Builder
|
||||
{
|
||||
return DB::table($this->table('visits'))->whereBetween('day', [$from, $to]);
|
||||
}
|
||||
|
||||
private function botHits(string $from, string $to): Builder
|
||||
{
|
||||
return DB::table($this->table('bot_hits'))->whereBetween('day', [$from, $to]);
|
||||
}
|
||||
|
||||
/** A count or sum as the database gives it (int, numeric string or null). */
|
||||
private function table(string $name): string
|
||||
{
|
||||
return Names::table($name);
|
||||
}
|
||||
|
||||
private static function number(mixed $value): int
|
||||
{
|
||||
return is_numeric($value) ? (int) $value : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class StatisticsController
|
||||
{
|
||||
public function index(Request $request, Statistics $statistics): JsonResponse
|
||||
{
|
||||
return response()->json($statistics->report($this->range($request), $this->choice($request)));
|
||||
}
|
||||
|
||||
/** One list of the period that is on the screen, as a CSV file. */
|
||||
public function export(Request $request, Statistics $statistics): StreamedResponse
|
||||
{
|
||||
$export = $statistics->export($request->string('sheet')->toString(), $this->range($request), $this->choice($request));
|
||||
|
||||
return response()->streamDownload(function () use ($export) {
|
||||
$out = fopen('php://output', 'w');
|
||||
|
||||
if ($out === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The mark that tells a spreadsheet the file is UTF-8.
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
fputcsv($out, $export['header'], ',', '"', '');
|
||||
|
||||
foreach ($export['rows'] as $row) {
|
||||
fputcsv($out, array_map(self::cell(...), $row), ',', '"', '');
|
||||
}
|
||||
|
||||
fclose($out);
|
||||
}, $export['filename'], ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store']);
|
||||
}
|
||||
|
||||
/**
|
||||
* A page address, a referring site and the name of a program come from visitors. A spreadsheet
|
||||
* runs a cell that starts like a formula, so such a cell gets a quote in front and is shown as
|
||||
* the text it is.
|
||||
*/
|
||||
private static function cell(string|int $value): string|int
|
||||
{
|
||||
return is_string($value) && preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value;
|
||||
}
|
||||
|
||||
private function range(Request $request): string
|
||||
{
|
||||
return $request->string('range', Statistics::DEFAULT_RANGE)->toString();
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function choice(Request $request): array
|
||||
{
|
||||
$choice = [];
|
||||
|
||||
foreach (['from', 'to', 'compare', 'compare_from'] as $key) {
|
||||
$choice[$key] = $request->string($key)->limit(20, '')->toString();
|
||||
}
|
||||
|
||||
// Nothing chosen is the period before, not "nothing".
|
||||
if ($choice['compare'] === '') {
|
||||
unset($choice['compare']);
|
||||
}
|
||||
|
||||
return $choice;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Contracts\Http\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/**
|
||||
* The site's own visitor statistics: page views, time on a page, where visitors came from, and the
|
||||
* programs that fetch pages. No cookies and no stored IP addresses. Off by default: the site
|
||||
* decides which of its addresses count (`manager.statistics.pages`, or a resolver of its own) and
|
||||
* puts the script that reports a page view on its pages.
|
||||
*/
|
||||
class StatisticsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'statistics';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Statistics';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['visitor_salts', 'visits', 'page_views', 'bot_hits'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [new Permission('statistics.view', 'See the visitor statistics and download them', 'Statistics')];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Statistics', 'route' => Names::route('statistics.index'), 'permission' => 'statistics.view']];
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [ForgetVisitorKeys::class];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return ['statistics.export' => ['Exported the statistics', ['sheet']]];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['statistics.index' => 'Opened the statistics'];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
app()->singleton(CountedPages::class);
|
||||
|
||||
// A person opens a few pages a minute; this only stops someone from flooding the statistics.
|
||||
RateLimiter::for('manager-pulse', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.statistics.per_minute', 120)))->by((string) $request->ip()));
|
||||
|
||||
// Programs never run the script that reports a view, so the server counts the pages it serves them.
|
||||
// Through the kernel: it copies its own groups to the router when a request starts.
|
||||
if (config('manager.statistics.count_bots') && method_exists($kernel = app(Kernel::class), 'appendMiddlewareToGroup')) {
|
||||
$kernel->appendMiddlewareToGroup('web', CountBots::class);
|
||||
}
|
||||
|
||||
// Without yesterday's key, yesterday's visitor codes can no longer be traced back.
|
||||
if (app()->runningInConsole()) {
|
||||
app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(ForgetVisitorKeys::class)->dailyAt('00:05'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\PageView;
|
||||
use IriksIT\Manager\Models\Visit;
|
||||
use IriksIT\Manager\Models\VisitorSalt;
|
||||
use IriksIT\Manager\Support\UserAgent;
|
||||
|
||||
/**
|
||||
* Writes down what the statistics are made of: a page that was looked at, the
|
||||
* visit it belongs to, and how long the visitor stayed on it. The only code that
|
||||
* writes to `visits` and `page_views`.
|
||||
*
|
||||
* The IP address and the browser line only go into the visitor code (see
|
||||
* VisitorSalt); neither is stored.
|
||||
*/
|
||||
final class VisitRecorder
|
||||
{
|
||||
/** A page view more than this long after the previous one starts a new visit. */
|
||||
public const VISIT_GAP_MINUTES = 30;
|
||||
|
||||
/** Nobody reads one page longer than this; a longer time is a tab left open. */
|
||||
public const MAX_SECONDS_ON_A_PAGE = 1800;
|
||||
|
||||
/**
|
||||
* Counts one page view. Returns the token the browser sends back when the
|
||||
* visitor leaves the page, or null when this is not something to count: a
|
||||
* program instead of a person, or an address that is not a page of the site.
|
||||
*
|
||||
* @param array{via?: string, campaign?: string, referrer?: string, country?: string, host?: string} $arrival how the visitor got here; only used for the first page of a visit
|
||||
*/
|
||||
public function view(string $ip, string $userAgent, string $path, array $arrival = []): ?string
|
||||
{
|
||||
$agent = new UserAgent($userAgent);
|
||||
$page = $this->page($path);
|
||||
|
||||
if ($agent->isBot() || $page === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$hash = hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent);
|
||||
|
||||
$visit = Visit::query()
|
||||
->where('visitor_hash', $hash)
|
||||
->where('last_seen_at', '>=', $now->copy()->subMinutes(self::VISIT_GAP_MINUTES))
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
if (! $visit instanceof Visit) {
|
||||
$source = Source::of($arrival['via'] ?? '', $arrival['campaign'] ?? '', $arrival['referrer'] ?? '', $arrival['host'] ?? '');
|
||||
$country = strtoupper(trim($arrival['country'] ?? ''));
|
||||
|
||||
$visit = Visit::query()->create([
|
||||
'visitor_hash' => $hash,
|
||||
'started_at' => $now,
|
||||
'last_seen_at' => $now,
|
||||
'day' => $now->toDateString(),
|
||||
'hour' => $now->hour,
|
||||
'weekday' => $now->dayOfWeekIso,
|
||||
'entry_path' => $page['path'],
|
||||
'exit_path' => $page['path'],
|
||||
'channel' => $source->channel,
|
||||
'source' => $source->source,
|
||||
'referrer_host' => $source->referrerHost,
|
||||
// Cloudflare says XX for unknown and T1 for Tor: neither is a country.
|
||||
'country' => preg_match('/^[A-Z]{2}$/', $country) === 1 && ! in_array($country, ['XX', 'T1'], true) ? $country : null,
|
||||
'device' => $agent->device(),
|
||||
'browser' => $agent->browser(),
|
||||
'os' => $agent->os(),
|
||||
]);
|
||||
}
|
||||
|
||||
$token = Str::random(40);
|
||||
|
||||
PageView::query()->create([
|
||||
'token' => $token,
|
||||
'visit_id' => $visit->id,
|
||||
'path' => $page['path'],
|
||||
'post_id' => $page['post_id'],
|
||||
'viewed_at' => $now,
|
||||
'day' => $now->toDateString(),
|
||||
'hour' => $now->hour,
|
||||
]);
|
||||
|
||||
$visit->update([
|
||||
'last_seen_at' => $now,
|
||||
'exit_path' => $page['path'],
|
||||
'page_views' => $visit->page_views + 1,
|
||||
]);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the visit of this visitor came from (channel and source), for a request
|
||||
* that is sent during it. Empty when the visit was not counted.
|
||||
*
|
||||
* @return array{channel?: string|null, source?: string|null}
|
||||
*/
|
||||
public function sourceOf(string $ip, string $userAgent): array
|
||||
{
|
||||
$visit = Visit::query()
|
||||
->where('visitor_hash', hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent))
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
return $visit instanceof Visit ? ['channel' => $visit->channel, 'source' => $visit->source] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The time a visitor had a page in view, reported when they leave it. The
|
||||
* browser may report more than once (a tab that is hidden and shown again),
|
||||
* each time with the total so far.
|
||||
*/
|
||||
public function leave(string $token, int $seconds): void
|
||||
{
|
||||
$view = PageView::query()->where('token', $token)->first();
|
||||
|
||||
if (! $view instanceof PageView || $seconds < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Never longer than the time that really passed since the page was opened.
|
||||
$passed = (int) abs(now()->diffInSeconds($view->viewed_at)) + 5;
|
||||
$seconds = min($seconds, $passed, self::MAX_SECONDS_ON_A_PAGE);
|
||||
|
||||
if ($seconds <= $view->seconds) {
|
||||
return;
|
||||
}
|
||||
|
||||
$view->update(['seconds' => $seconds]);
|
||||
|
||||
Visit::query()->whereKey($view->visit_id)->update([
|
||||
'seconds' => (int) PageView::query()->where('visit_id', $view->visit_id)->sum('seconds'),
|
||||
'last_seen_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The address as the statistics know it, or null when it is no public page of this site. */
|
||||
public function pathOf(string $path): ?string
|
||||
{
|
||||
return $this->page($path)['path'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page behind an address, or null when the address is not a public page
|
||||
* of this site: that keeps made-up addresses out of the statistics.
|
||||
*
|
||||
* @return array{path: string, post_id: int|null}|null
|
||||
*/
|
||||
private function page(string $path): ?array
|
||||
{
|
||||
if (! str_starts_with($path, '/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = '/'.trim(Str::before($path, '?'), '/');
|
||||
|
||||
if (strlen($path) > 255) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return app(CountedPages::class)->resolve($path);
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<?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 site's own visitor statistics. No cookie and no IP address: a visitor is a code made of the
|
||||
* IP address, the browser and a random key that is thrown away after a day, so the code cannot be
|
||||
* traced back to anyone afterwards.
|
||||
*
|
||||
* `day`, `hour` and `weekday` are plain columns in the site's own time, so no query needs a date
|
||||
* function and every query is the same on MySQL, PostgreSQL and SQLite. The moments are
|
||||
* `dateTime`, not `timestamp`: the MySQL of a server gives a `timestamp` that may not be null a
|
||||
* default by itself.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
|
||||
// The random key of a day. Yesterday's row is deleted: see VisitorSalt.
|
||||
Tables::create(Names::table('visitor_salts'), function (Blueprint $table) {
|
||||
$table->date('day')->primary();
|
||||
$table->string('salt', 64);
|
||||
});
|
||||
|
||||
// One visit: the pages someone looks at with less than half an hour between them.
|
||||
Tables::create(Names::table('visits'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('visitor_hash', 64);
|
||||
$table->dateTime('started_at');
|
||||
$table->dateTime('last_seen_at');
|
||||
$table->date('day');
|
||||
$table->unsignedTinyInteger('hour');
|
||||
// 1 = Monday ... 7 = Sunday.
|
||||
$table->unsignedTinyInteger('weekday');
|
||||
$table->string('entry_path');
|
||||
$table->string('exit_path');
|
||||
// direct, search, social, referral, share or campaign.
|
||||
$table->string('channel', 20);
|
||||
// The platform or site behind the channel: "linkedin", "google", "example.com".
|
||||
$table->string('source', 80)->nullable();
|
||||
$table->string('referrer_host')->nullable();
|
||||
$table->string('country', 2)->nullable();
|
||||
$table->string('device', 10);
|
||||
$table->string('browser', 30);
|
||||
$table->string('os', 20);
|
||||
$table->unsignedInteger('page_views')->default(0);
|
||||
$table->unsignedInteger('seconds')->default(0);
|
||||
|
||||
$table->index('day');
|
||||
$table->index(['visitor_hash', 'last_seen_at']);
|
||||
});
|
||||
|
||||
Tables::create(Names::table('page_views'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
// What the browser sends back when the visitor leaves the page, to report the time spent.
|
||||
$table->string('token', 40)->unique();
|
||||
$table->foreignId('visit_id')->constrained(Names::table('visits'))->cascadeOnDelete();
|
||||
$table->string('path');
|
||||
// The post behind the page, when the posts module is on. No foreign key: posts may be off.
|
||||
$table->unsignedBigInteger('post_id')->nullable();
|
||||
$table->dateTime('viewed_at');
|
||||
$table->date('day');
|
||||
$table->unsignedTinyInteger('hour');
|
||||
$table->unsignedInteger('seconds')->default(0);
|
||||
|
||||
$table->index('day');
|
||||
$table->index('path');
|
||||
});
|
||||
|
||||
// How often each program (search engine, AI crawler, link preview, ...) fetched each page, per
|
||||
// day. A counter, not a log: no address, no browser line.
|
||||
Tables::create(Names::table('bot_hits'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->date('day');
|
||||
$table->string('bot', 60);
|
||||
// search, ai, seo, social, monitor, feed, archive, scanner, script or other.
|
||||
$table->string('kind', 20);
|
||||
$table->string('path');
|
||||
$table->unsignedInteger('hits')->default(0);
|
||||
|
||||
$table->unique(['day', 'bot', 'path']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
|
||||
foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) {
|
||||
Schema::dropIfExists(Names::table($table));
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Statistics\PulseController;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
// Visitors of the public site report a page view here. No session, no cookies.
|
||||
// The script that does the reporting, and the component that puts it in a page: <x-manager::pulse />.
|
||||
Route::get(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/').'/pulse.js', [PulseController::class, 'script'])->name(Names::route('pulse.script'));
|
||||
|
||||
Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () {
|
||||
Route::post('/view', [PulseController::class, 'view'])->name(Names::route('pulse.view'));
|
||||
Route::post('/leave', [PulseController::class, 'leave'])->name(Names::route('pulse.leave'));
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Statistics\StatisticsController;
|
||||
|
||||
Route::get('/statistics', [StatisticsController::class, 'index'])->name('statistics.index')->middleware('can:statistics.view');
|
||||
Route::get('/statistics/export', [StatisticsController::class, 'export'])->name('statistics.export')->middleware('can:statistics.view');
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Updates;
|
||||
|
||||
use IriksIT\Manager\Support\Changelog;
|
||||
|
||||
class UpdatesController
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return response()->json(['releases' => Changelog::releases(limit: (int) config('manager.updates.limit', 20))]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Updates;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
/** What changed on the site: the releases of its CHANGELOG.md, as a screen. No tables. */
|
||||
class UpdatesModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'updates';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Updates';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [new Permission('updates.view', 'See what changed on the site', 'Site')];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [['label' => 'Updates', 'route' => Names::route('updates.index'), 'permission' => 'updates.view', 'simple' => true, 'hint' => 'What changed on your website']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['updates.index' => 'Opened the updates'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Updates\UpdatesController;
|
||||
|
||||
Route::get('/updates', [UpdatesController::class, 'index'])->name('updates.index')->middleware('can:updates.view');
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
|
||||
/**
|
||||
* The accounts of the manager and the groups each is in.
|
||||
*
|
||||
* Managing accounts must not be a way to more rights than one has. So, for anyone who is no
|
||||
* super admin: an account is only changed or deleted when it may do nothing more than oneself
|
||||
* (`managerOutranks`), and it is only put in a group that gives nothing more than one has
|
||||
* oneself (`managerMayGive`). Nobody becomes a super admin here: that is `manager:create-user`.
|
||||
*
|
||||
* The answers have the shape the screens of the sites used as props.
|
||||
*/
|
||||
class AccountController
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$model = $this->model();
|
||||
|
||||
return response()->json([
|
||||
'accounts' => $model::query()->with('managerGroups')->orderBy('name')->orderBy('id')->get()
|
||||
->map(fn ($user) => [
|
||||
'id' => $user->getKey(),
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
'is_super_admin' => $user->isManagerSuperAdmin(),
|
||||
'is_you' => $user->is($me),
|
||||
'view' => UserSetting::value($user, 'view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name, 'primary' => (bool) $group->pivot->is_primary])->values(),
|
||||
'can_change' => $me->managerOutranks($user),
|
||||
'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
|
||||
])->values(),
|
||||
'groups' => Group::query()->orderBy('name')->get()
|
||||
->map(fn (Group $group) => [
|
||||
'id' => $group->id,
|
||||
'name' => $group->name,
|
||||
'description' => $group->description,
|
||||
'can_give' => $me->managerMayGive($group),
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([...$this->rules(), 'password' => ['required', 'string', 'min:12', 'max:200']]);
|
||||
|
||||
// Everything is checked before anything is stored: a refused group leaves no account behind.
|
||||
$details = $this->details($request, null);
|
||||
$groups = $this->groups($request);
|
||||
|
||||
$model = $this->model();
|
||||
$user = new $model;
|
||||
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
|
||||
$user->managerGroups()->sync($this->withPrimary($groups, $request));
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['id' => $user->getKey()], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $account): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$user = $this->find($account);
|
||||
abort_unless($me->managerOutranks($user), 403);
|
||||
app(AuditTrail::class)->about($user);
|
||||
|
||||
$request->validate([...$this->rules(), 'password' => ['nullable', 'string', 'min:12', 'max:200']]);
|
||||
$details = $this->details($request, $user);
|
||||
|
||||
// Groups mean nothing for a super admin, and nobody changes their own.
|
||||
$groups = $user->isManagerSuperAdmin() || $user->is($me) ? null : $this->groups($request);
|
||||
|
||||
$user->forceFill($details);
|
||||
|
||||
// Empty: the password stays as it is.
|
||||
if ($request->filled('password')) {
|
||||
$user->forceFill(['password' => Hash::make($request->string('password')->toString())]);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
if ($groups !== null) {
|
||||
$user->managerGroups()->sync($this->withPrimary($groups, $request));
|
||||
}
|
||||
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request, string $account): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$user = $this->find($account);
|
||||
abort_unless($me->managerOutranks($user), 403);
|
||||
app(AuditTrail::class)->about($user);
|
||||
|
||||
if ($user->is($me)) {
|
||||
return response()->json(['message' => __('You cannot delete your own account.')], 422);
|
||||
}
|
||||
|
||||
$user->managerGroups()->detach();
|
||||
$user->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which face of the manager the account looks at (`full`, `simple`, or empty for what its rights give) and whether
|
||||
* it gets the tour at its next load. Only what the form sent is changed.
|
||||
*/
|
||||
private function settings(Request $request, $user): void
|
||||
{
|
||||
$values = [];
|
||||
|
||||
if ($request->exists('view')) {
|
||||
$values['view'] = $request->input('view') ?: null;
|
||||
}
|
||||
|
||||
if ($request->exists('tutorial')) {
|
||||
$values['tutorial'] = $request->boolean('tutorial') ? 'pending' : (UserSetting::value($user, 'tutorial') === 'pending' ? 'skipped' : UserSetting::value($user, 'tutorial'));
|
||||
}
|
||||
|
||||
if ($values !== []) {
|
||||
UserSetting::put($user, $values);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return class-string<Authenticatable&Model> */
|
||||
private function model(): string
|
||||
{
|
||||
return config('manager.user_model');
|
||||
}
|
||||
|
||||
private function find(string $id)
|
||||
{
|
||||
return $this->model()::query()->findOrFail($id);
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
private function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'groups' => ['array'],
|
||||
'groups.*' => ['integer'],
|
||||
'primary_group' => ['nullable', 'integer'],
|
||||
'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])],
|
||||
'tutorial' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Name and email address, the address in lower case and not in use by another account.
|
||||
*
|
||||
* @return array{name: string, email: string}
|
||||
*/
|
||||
private function details(Request $request, $user): array
|
||||
{
|
||||
$email = $request->string('email')->trim()->lower()->toString();
|
||||
|
||||
if ($this->model()::query()->where('email', $email)->when($user !== null, fn ($query) => $query->whereKeyNot($user->getKey()))->exists()) {
|
||||
throw ValidationException::withMessages(['email' => __('Another account already uses this email address.')]);
|
||||
}
|
||||
|
||||
return ['name' => $request->string('name')->trim()->toString(), 'email' => $email];
|
||||
}
|
||||
|
||||
/**
|
||||
* The ticked groups as a sync map: exactly one of them is the primary one (the one that was asked for, else the first),
|
||||
* and none when there are no groups.
|
||||
*
|
||||
* @param list<int> $ids
|
||||
* @return array<int, array{is_primary: bool}>
|
||||
*/
|
||||
private function withPrimary(array $ids, Request $request): array
|
||||
{
|
||||
$asked = $request->integer('primary_group');
|
||||
$primary = in_array($asked, $ids, true) ? $asked : ($ids[0] ?? null);
|
||||
|
||||
return collect($ids)->mapWithKeys(fn (int $id) => [$id => ['is_primary' => $id === $primary]])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the groups that were ticked. One that does not exist, or that gives more than
|
||||
* the account that is logged in has, is refused.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function groups(Request $request): array
|
||||
{
|
||||
$me = $request->user();
|
||||
$ids = array_values(array_unique(array_map(fn (mixed $id) => is_numeric($id) ? (int) $id : 0, $request->array('groups'))));
|
||||
$groups = Group::query()->whereKey($ids)->get();
|
||||
|
||||
if ($groups->count() !== count($ids) || $groups->contains(fn (Group $group) => ! $me->managerMayGive($group))) {
|
||||
throw ValidationException::withMessages(['groups' => __('You can only choose groups that allow nothing more than your own account.')]);
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
/**
|
||||
* Creates a super admin: an account that may do everything in the manager, and the only kind
|
||||
* that manages the groups. This is the only place that hands out `is_super_admin`.
|
||||
*
|
||||
* php artisan manager:create-user
|
||||
*
|
||||
* It asks for name, email and password. For scripts, pass them as options.
|
||||
*/
|
||||
class CreateManagerUser extends Command
|
||||
{
|
||||
protected $signature = 'manager:create-user
|
||||
{--name= : Name shown in the manager}
|
||||
{--email= : Email address to log in with}
|
||||
{--password= : Password (min 12 characters); leave out to type it hidden}';
|
||||
|
||||
protected $description = 'Create a super admin: an account that may do everything in the manager';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$name = $this->value('name', 'Name');
|
||||
$email = strtolower($this->value('email', 'Email'));
|
||||
$password = $this->value('password', 'Password (min 12 characters)', secret: true);
|
||||
$model = config('manager.user_model');
|
||||
|
||||
if ($name === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
||||
$this->error('A name and a valid email address are required.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($model::query()->where('email', $email)->exists()) {
|
||||
$this->error("A user with email {$email} already exists.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (mb_strlen($password) < 12) {
|
||||
$this->error('Password must be at least 12 characters.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Direct assignment: a super admin is never mass-assignable.
|
||||
$user = new $model;
|
||||
$user->forceFill(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
|
||||
$user->is_super_admin = true;
|
||||
$user->save();
|
||||
|
||||
$this->info("Super admin account for {$name} <{$email}> created.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/** The option when it was given, otherwise the answer to a question. */
|
||||
private function value(string $option, string $question, bool $secret = false): string
|
||||
{
|
||||
$given = $this->option($option);
|
||||
|
||||
if (is_string($given) && trim($given) !== '') {
|
||||
return $secret ? $given : trim($given);
|
||||
}
|
||||
|
||||
$answer = $secret ? $this->secret($question) : $this->ask($question);
|
||||
|
||||
if (! is_string($answer)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $secret ? $answer : trim($answer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */
|
||||
class GroupController
|
||||
{
|
||||
public function __construct(private readonly ModuleRegistry $modules) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'groups' => Group::query()->withCount('users')->orderBy('name')->get()
|
||||
->map(fn (Group $group) => [
|
||||
'id' => $group->id,
|
||||
'name' => $group->name,
|
||||
'description' => $group->description,
|
||||
'start' => $group->start,
|
||||
'permissions' => $group->allowed(),
|
||||
'accounts' => $group->users_count,
|
||||
])->values(),
|
||||
'catalogue' => $this->modules->catalogue(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$group = Group::create($this->validated($request));
|
||||
|
||||
return response()->json(['id' => $group->id], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $group): JsonResponse
|
||||
{
|
||||
$group = Group::query()->findOrFail($group);
|
||||
app(AuditTrail::class)->about($group);
|
||||
$group->update($this->validated($request, $group));
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
/** The accounts in it stay; they lose what only this group allowed. */
|
||||
public function destroy(string $group): JsonResponse
|
||||
{
|
||||
$group = Group::query()->findOrFail($group);
|
||||
app(AuditTrail::class)->about($group);
|
||||
$group->users()->detach();
|
||||
$group->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return array{name: string, description: string|null, start: string|null, permissions: list<string>} */
|
||||
private function validated(Request $request, ?Group $group = null): array
|
||||
{
|
||||
$table = Names::table('groups');
|
||||
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'start' => ['nullable', 'string', 'max:200', 'regex:#^/[A-Za-z0-9/_.-]*$#'],
|
||||
'permissions' => ['array'],
|
||||
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
|
||||
]);
|
||||
|
||||
$description = $request->string('description')->trim()->toString();
|
||||
|
||||
return [
|
||||
'name' => $request->string('name')->trim()->toString(),
|
||||
'description' => $description !== '' ? $description : null,
|
||||
'start' => $request->filled('start') ? $request->string('start')->toString() : null,
|
||||
'permissions' => $this->modules->complete($request->array('permissions')),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class UsersModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'users';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Users';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['groups', 'group_user'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('accounts.manage', 'Create, change and delete accounts, and put them in groups', 'Accounts'),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Accounts', 'route' => Names::route('accounts.index'), 'permission' => 'accounts.manage'],
|
||||
['label' => 'Groups', 'route' => Names::route('groups.index'), 'permission' => 'groups.manage'],
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [
|
||||
'accounts.store' => ['Created an account'],
|
||||
'accounts.update' => ['Changed an account'],
|
||||
'accounts.destroy' => ['Deleted an account'],
|
||||
'groups.store' => ['Created a group'],
|
||||
'groups.update' => ['Changed a group'],
|
||||
'groups.destroy' => ['Deleted a group'],
|
||||
];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['accounts.index' => 'Opened the accounts', 'groups.index' => 'Opened the groups'];
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [CreateManagerUser::class];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?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();
|
||||
|
||||
// New accounts are never super admins; an existing one is not promoted here.
|
||||
// `manager:create-user` is the way to make a super admin.
|
||||
if (! Schema::hasColumn($users, 'is_super_admin')) {
|
||||
Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false));
|
||||
}
|
||||
|
||||
Tables::create(Names::table('groups'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name')->unique();
|
||||
$table->string('description', 500)->nullable();
|
||||
$table->json('permissions')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Tables::create(Names::table('group_user'), function (Blueprint $table) use ($users) {
|
||||
$table->foreignId('group_id')->constrained(Names::table('groups'))->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->constrained($users)->cascadeOnDelete();
|
||||
$table->primary(['group_id', 'user_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$users = (new (config('manager.user_model')))->getTable();
|
||||
|
||||
Schema::dropIfExists(Names::table('group_user'));
|
||||
Schema::dropIfExists(Names::table('groups'));
|
||||
Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Tables::addColumn(Names::table('group_user'), 'is_primary', fn (Blueprint $table) => $table->boolean('is_primary')->default(false));
|
||||
Tables::addColumn(Names::table('groups'), 'start', fn (Blueprint $table) => $table->string('start', 200)->nullable());
|
||||
|
||||
// An account that is in groups already gets the first of them as its primary one.
|
||||
$pivot = Names::table('group_user');
|
||||
|
||||
$hasPrimary = DB::table($pivot)->where('is_primary', true)->exists();
|
||||
foreach ($hasPrimary ? [] : DB::table($pivot)->select('user_id', DB::raw('min(group_id) as first'))->groupBy('user_id')->get() as $row) {
|
||||
DB::table($pivot)->where('user_id', $row->user_id)->where('group_id', $row->first)->update(['is_primary' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->dropColumn('start'));
|
||||
Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->dropColumn('is_primary'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Users\AccountController;
|
||||
use IriksIT\Manager\Modules\Users\GroupController;
|
||||
|
||||
// `{account}` and `{group}` are resolved in the controllers: the user model is configurable,
|
||||
// so nothing is bound globally.
|
||||
Route::middleware('can:accounts.manage')->group(function () {
|
||||
Route::get('/accounts', [AccountController::class, 'index'])->name('accounts.index');
|
||||
Route::post('/accounts', [AccountController::class, 'store'])->name('accounts.store');
|
||||
Route::put('/accounts/{account}', [AccountController::class, 'update'])->name('accounts.update')->whereNumber('account');
|
||||
Route::delete('/accounts/{account}', [AccountController::class, 'destroy'])->name('accounts.destroy')->whereNumber('account');
|
||||
});
|
||||
|
||||
Route::middleware('can:groups.manage')->group(function () {
|
||||
Route::get('/groups', [GroupController::class, 'index'])->name('groups.index');
|
||||
Route::post('/groups', [GroupController::class, 'store'])->name('groups.store');
|
||||
Route::put('/groups/{group}', [GroupController::class, 'update'])->name('groups.update')->whereNumber('group');
|
||||
Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy')->whereNumber('group');
|
||||
});
|
||||
Reference in new issue
Block a user