v0.9.0
This commit is contained in:
commit
860182098c
277 files changed
+18338
No files matched your search
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\AuditLog;
|
||||
|
||||
/**
|
||||
* The audit log: who logged in, who failed to, and who did what in the manager. The only code
|
||||
* that writes the log. Every line carries the address and the browser line of the request it came
|
||||
* from; that is what the log is for, and why only accounts with "audit.view" get to see it.
|
||||
*
|
||||
* Never write what was typed into a form here (a password could be in it): a line says what was
|
||||
* done to what.
|
||||
*/
|
||||
final class AuditTrail
|
||||
{
|
||||
/** The first thing that was made during this request. */
|
||||
private ?Model $made = null;
|
||||
|
||||
/** A controller said what the request is about: what is made after that does not change it. */
|
||||
private bool $settled = false;
|
||||
|
||||
/** Start of a request: forget what the one before made. */
|
||||
public function reset(): void
|
||||
{
|
||||
$this->made = null;
|
||||
$this->settled = false;
|
||||
}
|
||||
|
||||
public function made(Model $model): void
|
||||
{
|
||||
if (! $this->settled && $this->made === null && ! $model instanceof AuditLog) {
|
||||
$this->made = $model;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For a controller whose request is about something it did not make (an address that was
|
||||
* banned before, an account that was changed), or about no single thing (null).
|
||||
*/
|
||||
public function about(?Model $model): void
|
||||
{
|
||||
$this->made = $model;
|
||||
$this->settled = true;
|
||||
}
|
||||
|
||||
public function firstMade(): ?Model
|
||||
{
|
||||
return $this->made;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $details
|
||||
*/
|
||||
public function record(
|
||||
string $event,
|
||||
string $summary,
|
||||
?Authenticatable $user = null,
|
||||
?Model $subject = null,
|
||||
array $details = [],
|
||||
?string $action = null,
|
||||
?string $email = null,
|
||||
): AuditLog {
|
||||
// A command has no visitor: no address and no browser.
|
||||
$request = app()->runningInConsole() && ! app()->runningUnitTests() ? null : request();
|
||||
$about = $subject === null ? null : self::describe($subject);
|
||||
$agent = $request?->userAgent();
|
||||
$name = $user === null ? null : data_get($user, 'name');
|
||||
|
||||
return AuditLog::query()->create([
|
||||
'event' => $event,
|
||||
'action' => $action,
|
||||
'summary' => Str::limit($summary, 250, '…'),
|
||||
'subject_type' => $about['type'] ?? null,
|
||||
'subject_id' => $about['id'] ?? null,
|
||||
'subject_label' => $about['label'] ?? null,
|
||||
'details' => $details === [] ? null : $details,
|
||||
'user_id' => $user?->getAuthIdentifier(),
|
||||
'user_name' => is_string($name) ? $name : null,
|
||||
'email' => $email === null ? null : Str::limit($email, 250, '…'),
|
||||
'ip' => $request?->ip(),
|
||||
'user_agent' => is_string($agent) ? Str::limit($agent, 490, '…') : null,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a model is called in the log: its kind ('post', 'ip_ban'), its id and a name.
|
||||
*
|
||||
* @return array{type: string, id: int|null, label: string}
|
||||
*/
|
||||
public static function describe(Model $model): array
|
||||
{
|
||||
$id = $model->getKey();
|
||||
$id = is_int($id) ? $id : null;
|
||||
$label = '#'.($id ?? '?');
|
||||
|
||||
foreach (['title', 'name', 'label', 'ip', 'slug'] as $attribute) {
|
||||
$value = $model->getAttribute($attribute);
|
||||
|
||||
if (is_string($value) && trim($value) !== '') {
|
||||
$label = Str::limit(trim($value), 200, '…');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ['type' => Str::snake(class_basename($model)), 'id' => $id, 'label' => $label];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* The live preview of a page: the blocks that are not saved yet, kept for a few minutes under a signed token, and shown by the real
|
||||
* public page. The editor posts the blocks, gets back the address of the public page with `?mb-preview=<token>`, and shows that in a frame.
|
||||
*
|
||||
* `Blocks::for($slug)` uses the preview blocks by itself when the request carries a token that is signed, not expired and made for that
|
||||
* page, **and** the person is logged in with `pages.edit`. Nobody else can read a draft, whatever token they hold. It works the same for
|
||||
* Inertia, Blade and the page API, as long as the request has the session of the person (a frontend on another origin has no session and
|
||||
* gets the saved blocks; it can build its own preview mode from the schema).
|
||||
*/
|
||||
final class BlockPreview
|
||||
{
|
||||
public const PARAMETER = 'mb-preview';
|
||||
|
||||
/** Whether the editor offers a preview: the site switched it on in `manager.blocks.preview`. */
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return (bool) config('manager.blocks.preview.enabled', false);
|
||||
}
|
||||
|
||||
/** The public address of a page: the pattern in `manager.blocks.preview.url` (`/{slug}`, the home page is `/`), or an invokable class of the site. */
|
||||
public static function address(string $slug): string
|
||||
{
|
||||
$setting = config('manager.blocks.preview.url');
|
||||
|
||||
if (is_string($setting) && $setting !== '' && ! str_contains($setting, '{slug}') && class_exists($setting) && is_callable(new $setting)) {
|
||||
return (string) (new $setting)($slug);
|
||||
}
|
||||
|
||||
$pattern = is_string($setting) && $setting !== '' ? $setting : '/{slug}';
|
||||
|
||||
return $slug === config('manager.blocks.preview.home', 'home') && $setting === null ? '/' : str_replace('{slug}', $slug, $pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the blocks and returns the token with the address to show them at.
|
||||
*
|
||||
* @param array<array-key, mixed> $blocks
|
||||
* @param list<string> $allowed the types the page may hold
|
||||
* @return array{token: string, url: string, expires_at: int}
|
||||
*/
|
||||
public static function store(string $slug, array $blocks, array $allowed): array
|
||||
{
|
||||
$clean = Blocks::clean($blocks, $allowed);
|
||||
$json = (string) json_encode($clean);
|
||||
|
||||
abort_if(strlen($json) > max(1, (int) config('manager.blocks.preview.max_kb', 512)) * 1024, 422, __('This page is too big to preview.'));
|
||||
|
||||
$ttl = max(60, (int) config('manager.blocks.preview.ttl', 600));
|
||||
$id = strtolower((string) Str::ulid());
|
||||
$expires = time() + $ttl;
|
||||
|
||||
Cache::put(self::key($id), $clean, $ttl);
|
||||
|
||||
$token = $id.'.'.$expires.'.'.self::sign($id, $slug, $expires);
|
||||
|
||||
return ['token' => $token, 'url' => self::address($slug).(str_contains(self::address($slug), '?') ? '&' : '?').self::PARAMETER.'='.$token, 'expires_at' => $expires];
|
||||
}
|
||||
|
||||
/**
|
||||
* The blocks of the preview this request asks for, or null: no token, a wrong or expired one, one for another page, no person logged in
|
||||
* with `pages.edit`, or the blocks are gone from the cache.
|
||||
*
|
||||
* @return ?list<array<string, mixed>>
|
||||
*/
|
||||
public static function current(string $slug): ?array
|
||||
{
|
||||
if (! self::enabled() || ! app()->bound('request')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$token = request()->query(self::PARAMETER);
|
||||
|
||||
if (! is_string($token) || substr_count($token, '.') !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$id, $expires, $signature] = explode('.', $token);
|
||||
|
||||
if (! preg_match('/^[0-9a-z]{26}$/', $id) || ! ctype_digit($expires) || (int) $expires < time() || ! hash_equals(self::sign($id, $slug, (int) $expires), $signature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! Gate::allows('pages.edit')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$blocks = Cache::get(self::key($id));
|
||||
|
||||
return is_array($blocks) ? $blocks : null;
|
||||
}
|
||||
|
||||
private static function key(string $id): string
|
||||
{
|
||||
return 'manager:block-preview:'.$id;
|
||||
}
|
||||
|
||||
private static function sign(string $id, string $slug, int $expires): string
|
||||
{
|
||||
return hash_hmac('sha256', $id.'|'.$slug.'|'.$expires, (string) config('app.key'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\BlockTemplate;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Support\Blocks\CoreTypes;
|
||||
|
||||
/**
|
||||
* The blocks of a page: an ordered list of `{id, type, data, style, hidden}`. A block type has fields (the types of `Fields`) and
|
||||
* style options chosen from sets the site defines (`manager.blocks.tokens`); the site draws a block with its own view or component.
|
||||
*
|
||||
* A site adds block types in `manager.blocks.types` (or `Blocks::register()`), and replaces a shipped one by using its key.
|
||||
* `Blocks::for('home')` is what the public site reads; the manager screen reads `Blocks::catalogue()` and `Blocks::forEditor()`.
|
||||
* See `docs/design/page-builder.md` in the repository.
|
||||
*/
|
||||
final class Blocks
|
||||
{
|
||||
/** @var array<string, array<string, mixed>> */
|
||||
private static array $extra = [];
|
||||
|
||||
/** @param array<string, mixed> $definition see `Blocks\CoreTypes` */
|
||||
public static function register(string $key, array $definition): void
|
||||
{
|
||||
self::$extra[$key] = $definition;
|
||||
}
|
||||
|
||||
public static function forgetRegistered(): void
|
||||
{
|
||||
self::$extra = [];
|
||||
}
|
||||
|
||||
/** The choices of every style option: what ships, over which the site sets its own. @return array<string, array<string, string>> */
|
||||
public static function tokens(): array
|
||||
{
|
||||
$out = CoreTypes::tokens();
|
||||
|
||||
foreach ((array) config('manager.blocks.tokens', []) as $name => $choices) {
|
||||
if (is_string($name) && is_array($choices) && $choices !== []) {
|
||||
$out[$name] = array_map('strval', $choices);
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every block type that is available now: a type of a feature that is off is not there.
|
||||
*
|
||||
* @return array<string, array{key: string, label: string, simple_label: ?string, group: string, icon: string, style: list<string>, resolves: ?string, fields: array<string, array<string, mixed>>}>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
$definitions = array_replace(CoreTypes::all(), (array) config('manager.blocks.types', []), self::$extra);
|
||||
$tokens = self::tokens();
|
||||
$out = [];
|
||||
|
||||
foreach ($definitions as $key => $definition) {
|
||||
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || ! is_array($definition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($definition['feature']) && ! Features::on((string) $definition['feature'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = (array) ($definition['fields'] ?? []);
|
||||
|
||||
// A block that shows the records of a list offers the lists the site has.
|
||||
if (($definition['resolves'] ?? null) === 'list' && isset($fields['source'])) {
|
||||
$fields['source']['options'] = array_map(fn (array $resource) => $resource['label'], Resources::all());
|
||||
}
|
||||
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'simple_label' => Fields::simpleText($definition, 'label'),
|
||||
'group' => (string) ($definition['group'] ?? 'Content'),
|
||||
'icon' => (string) ($definition['icon'] ?? $key),
|
||||
'style' => array_values(array_filter((array) ($definition['style'] ?? []), fn ($name) => is_string($name) && isset($tokens[$name]))),
|
||||
'resolves' => isset($definition['resolves']) ? (string) $definition['resolves'] : null,
|
||||
'fields' => Fields::normalize($fields),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the screen needs to offer the types (the fields as the form builds them, and the style choices).
|
||||
*
|
||||
* @param ?list<string> $allowed null: every type
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function catalogue(?array $allowed = null): array
|
||||
{
|
||||
$tokens = self::tokens();
|
||||
$out = [];
|
||||
|
||||
foreach (self::types() as $key => $type) {
|
||||
if ($allowed !== null && ! in_array($key, $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$out[] = [
|
||||
'key' => $key,
|
||||
'label' => $type['label'],
|
||||
'simple_label' => $type['simple_label'],
|
||||
'group' => $type['group'],
|
||||
'icon' => $type['icon'],
|
||||
'fields' => Fields::described($type['fields']),
|
||||
'style' => array_map(fn (string $name) => ['key' => $name, 'options' => $tokens[$name], 'default' => array_key_first($tokens[$name])], $type['style']),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What may be saved: unknown types and types a page does not allow are dropped, the data is cleaned by the fields of the type, the
|
||||
* style options are kept to the choices there are, and every block gets an id.
|
||||
*
|
||||
* @param array<array-key, mixed> $input
|
||||
* @param ?list<string> $allowed
|
||||
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, hidden: bool}>
|
||||
*/
|
||||
public static function clean(array $input, ?array $allowed = null): array
|
||||
{
|
||||
$types = self::types();
|
||||
$max = max(1, (int) config('manager.blocks.max', 100));
|
||||
$out = [];
|
||||
|
||||
foreach ($input as $block) {
|
||||
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
||||
|
||||
if ($type === null || ! isset($types[$type]) || ($allowed !== null && ! in_array($type, $allowed, true))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$out[] = [
|
||||
'id' => self::id($block['id'] ?? null),
|
||||
'type' => $type,
|
||||
'data' => Fields::clean($types[$type]['fields'], (array) ($block['data'] ?? [])),
|
||||
'style' => self::style($types[$type], (array) ($block['style'] ?? [])),
|
||||
'hidden' => filter_var($block['hidden'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
||||
];
|
||||
|
||||
if (count($out) >= $max) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation rules for the blocks of a request, keyed `blocks`, `blocks.<i>.…`.
|
||||
*
|
||||
* @param array<array-key, mixed> $input
|
||||
* @param ?list<string> $allowed
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function rules(array $input, ?array $allowed = null, bool $bindings = false): array
|
||||
{
|
||||
$types = self::types();
|
||||
$rules = [
|
||||
'blocks' => ['nullable', 'array', 'max:'.max(1, (int) config('manager.blocks.max', 100))],
|
||||
'blocks.*' => ['array'],
|
||||
'blocks.*.type' => ['required', 'string', 'max:40'],
|
||||
'blocks.*.id' => ['nullable', 'string', 'max:40'],
|
||||
'blocks.*.hidden' => ['boolean'],
|
||||
'blocks.*.style' => ['nullable', 'array'],
|
||||
'blocks.*.data' => ['nullable', 'array'],
|
||||
];
|
||||
|
||||
foreach ($input as $index => $block) {
|
||||
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
||||
|
||||
if ($type !== null && isset($types[$type]) && ($allowed === null || in_array($type, $allowed, true))) {
|
||||
$fieldRules = Fields::rules($types[$type]['fields'], "blocks.{$index}.data.");
|
||||
$rules = [...$rules, ...($bindings ? self::allowBindings($fieldRules) : $fieldRules)];
|
||||
}
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a page layout: an address or picture may also begin with `{record.<field>}` (the value is checked when it is drawn).
|
||||
*
|
||||
* @param array<string, list<mixed>> $rules
|
||||
* @return array<string, list<mixed>>
|
||||
*/
|
||||
private static function allowBindings(array $rules): array
|
||||
{
|
||||
$address = 'regex:'.Fields::ADDRESS;
|
||||
$binding = '#^\{record\.[a-z][a-z0-9_]*\}[^\s<>"\']*$#i';
|
||||
|
||||
return array_map(fn (array $list) => array_map(fn ($rule) => $rule === $address
|
||||
? function (string $attribute, mixed $value, \Closure $fail) use ($binding): void {
|
||||
if (! is_string($value) || (preg_match(Fields::ADDRESS, $value) !== 1 && preg_match($binding, $value) !== 1)) {
|
||||
$fail(__('The :attribute must be a web address, a path of the site or {record.<field>}.', ['attribute' => $attribute]));
|
||||
}
|
||||
}
|
||||
: $rule, $list), $rules);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored blocks as the editor shows them: every block of a known type, hidden ones too, every field with its value.
|
||||
*
|
||||
* @param array<array-key, mixed> $stored
|
||||
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, hidden: bool}>
|
||||
*/
|
||||
public static function forEditor(array $stored): array
|
||||
{
|
||||
$types = self::types();
|
||||
$out = [];
|
||||
|
||||
foreach ($stored as $block) {
|
||||
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
||||
|
||||
if ($type === null || ! isset($types[$type])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$out[] = [
|
||||
'id' => self::id($block['id'] ?? null),
|
||||
'type' => $type,
|
||||
'data' => Fields::values($types[$type]['fields'], (array) ($block['data'] ?? [])),
|
||||
'style' => self::style($types[$type], (array) ($block['style'] ?? [])),
|
||||
'hidden' => (bool) ($block['hidden'] ?? false),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the public site draws for a page: the visible blocks in order, each with its data (defaults filled in) and style, and, for a
|
||||
* block that shows a list, the records of that list. A block of a feature that is off, or of a list that is gone, is left out.
|
||||
*
|
||||
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, items?: list<array<string, mixed>>}>
|
||||
*/
|
||||
public static function for(string $slug): array
|
||||
{
|
||||
// A person editing the page sees the blocks of the preview they asked for, not the saved ones.
|
||||
$saved = Page::query()->where('slug', $slug)->first()?->blocks;
|
||||
$stored = BlockPreview::current($slug) ?? (is_array($saved) ? $saved : []);
|
||||
|
||||
return self::render($stored, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The page of one record (a service, a project): the blocks of the page layout of its list (`manager.resources.<key>.template`),
|
||||
* with `{record.<field>}` in the text, address and picture fields filled in from the record, as `for()` gives them. A `cards` block
|
||||
* can show only what belongs to the record (`match_list` = `match_record`) and leave the record itself out. Empty when the list
|
||||
* has no page layout, is off, or the record is not active.
|
||||
*
|
||||
* @param Eloquent|array{id: mixed, values: array<string, mixed>} $record a model of the list, or `Resources::row()`
|
||||
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, items?: list<array<string, mixed>>}>
|
||||
*/
|
||||
public static function forRecord(string $resource, Eloquent|array $record): array
|
||||
{
|
||||
$definition = Resources::find($resource);
|
||||
|
||||
if ($definition === null || $definition['template'] === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$row = $record instanceof Eloquent ? Resources::row($definition, $record) : $record;
|
||||
|
||||
if (! ($row['values']['is_active'] ?? true)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$template = BlockTemplate::query()->where('resource', $resource)->first();
|
||||
$allowed = self::templateTypes($resource);
|
||||
|
||||
return self::render(is_array($template?->blocks) ? $template->blocks : [], ['resource' => $resource, 'row' => $row], $allowed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The block types the page layout of a list may use (`manager.resources.<key>.template`: `true` for all, or a list). Empty without one.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function templateTypes(string $resource): array
|
||||
{
|
||||
$allowed = Resources::find($resource)['template'] ?? false;
|
||||
$known = array_keys(self::types());
|
||||
|
||||
if ($allowed === true) {
|
||||
return $known;
|
||||
}
|
||||
|
||||
return is_array($allowed) ? array_values(array_intersect($known, $allowed)) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $stored
|
||||
* @param ?array{resource: string, row: array{id: mixed, values: array<string, mixed>}} $context the record a page layout is drawn for
|
||||
* @param ?list<string> $allowed
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private static function render(array $stored, ?array $context, ?array $allowed = null): array
|
||||
{
|
||||
$types = self::types();
|
||||
$out = [];
|
||||
|
||||
foreach (self::forEditor($stored) as $block) {
|
||||
if ($block['hidden'] || ($allowed !== null && ! in_array($block['type'], $allowed, true))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = $types[$block['type']]['fields'];
|
||||
$data = $context === null ? $block['data'] : self::bind($fields, $block['data'], $context['row']);
|
||||
$entry = ['id' => $block['id'], 'type' => $block['type'], 'data' => self::withHtml($fields, $data), 'style' => $block['style']];
|
||||
|
||||
if ($types[$block['type']]['resolves'] === 'list') {
|
||||
$items = self::items($data, $context);
|
||||
|
||||
if ($items === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry['items'] = $items;
|
||||
}
|
||||
|
||||
$out[] = $entry;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{record.<field>}` in the text, address and picture fields of a block (also in a list or a repeater) becomes the value of that
|
||||
* field of the record, or nothing when the record has no such field. The value is text like any other: it is escaped when it is drawn,
|
||||
* Markdown cannot carry HTML, and an address or picture that comes out unsafe becomes `#` (an address) or nothing (a picture).
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<string, mixed> $data
|
||||
* @param array{id: mixed, values: array<string, mixed>} $row
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function bind(array $fields, array $data, array $row): array
|
||||
{
|
||||
$values = ['id' => $row['id']] + $row['values'];
|
||||
$fill = function (string $text) use ($values): string {
|
||||
return (string) preg_replace_callback('/\{record\.([a-z][a-z0-9_]*)\}/', function (array $match) use ($values): string {
|
||||
$value = $values[$match[1]] ?? null;
|
||||
|
||||
return is_scalar($value) ? (is_bool($value) ? ($value ? '1' : '') : (string) $value) : '';
|
||||
}, $text);
|
||||
};
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$value = $data[$key] ?? null;
|
||||
|
||||
switch ($field['type']) {
|
||||
case 'text': case 'textarea': case 'markdown':
|
||||
$data[$key] = is_string($value) ? $fill($value) : $value;
|
||||
break;
|
||||
case 'url': case 'media':
|
||||
if (is_string($value) && str_contains($value, '{record.')) {
|
||||
$address = self::safeUrl($fill($value));
|
||||
$data[$key] = $address === '#' && $field['type'] === 'media' ? '' : $address;
|
||||
}
|
||||
break;
|
||||
case 'list': case 'media_list':
|
||||
$data[$key] = is_array($value) ? array_map(function ($item) use ($fill, $field) {
|
||||
if (! is_string($item) || ! str_contains($item, '{record.')) {
|
||||
return $item;
|
||||
}
|
||||
|
||||
$filled = $fill($item);
|
||||
|
||||
return $field['type'] === 'media_list' ? (self::safeUrl($filled) === '#' ? '' : $filled) : $filled;
|
||||
}, $value) : $value;
|
||||
break;
|
||||
case 'repeater':
|
||||
$data[$key] = is_array($value) ? array_map(fn ($row2) => is_array($row2) ? self::bind($field['items'], $row2, $row) : $row2, $value) : $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown fields come with their safe HTML next to them: `body` gets a `body_html`. Raw HTML in the text is escaped by `Markdown`, so a
|
||||
* frontend may print `*_html` as it is and must print everything else as text. The same goes for a repeater with a markdown field.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function withHtml(array $fields, array $data): array
|
||||
{
|
||||
foreach ($fields as $key => $field) {
|
||||
if ($field['type'] === 'markdown') {
|
||||
$data[$key.'_html'] = Markdown::toHtml((string) ($data[$key] ?? ''));
|
||||
} elseif ($field['type'] === 'repeater' && is_array($data[$key] ?? null)) {
|
||||
$data[$key] = array_map(fn ($row) => is_array($row) ? self::withHtml($field['items'], $row) : $row, $data[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** The view that draws a block type: one of the site (`resources/views/blocks/<type>.blade.php`), else the package's. Null when there is none. */
|
||||
public static function view(string $type): ?string
|
||||
{
|
||||
if (preg_match('/^[a-z][a-z0-9_]{0,39}$/', $type) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (["blocks.{$type}", "manager::blocks.{$type}"] as $view) {
|
||||
if (view()->exists($view)) {
|
||||
return $view;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** CSS classes for the style options of a block: `mb--background-dark mb--width-wide`. */
|
||||
public static function classes(array $style): string
|
||||
{
|
||||
$classes = [];
|
||||
|
||||
foreach ($style as $name => $value) {
|
||||
$classes[] = 'mb--'.preg_replace('/[^a-z0-9_-]/i', '', (string) $name).'-'.preg_replace('/[^a-z0-9_-]/i', '', (string) $value);
|
||||
}
|
||||
|
||||
return implode(' ', $classes);
|
||||
}
|
||||
|
||||
/** An address that is safe in an `href` or `src`: http(s), a path, `mailto:`, `tel:` or an anchor; anything else becomes `#`. */
|
||||
public static function safeUrl(mixed $url): string
|
||||
{
|
||||
$url = is_string($url) ? trim($url) : '';
|
||||
|
||||
// No quote, bracket, backslash or space either: the address may end up in an attribute or in a CSS `url()`.
|
||||
return preg_match('~^(https?://|/(?!/)|#|mailto:|tel:)~i', $url) === 1 && preg_match('~[\s"\'()<>\\\\]~', $url) !== 1 ? $url : '#';
|
||||
}
|
||||
|
||||
/**
|
||||
* Structured data for search engines that the blocks of a page give: a `faq` block is a `FAQPage`. Print each as JSON in
|
||||
* `<script type="application/ld+json">` (the Blade view of the `faq` block does it itself).
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks from `for()`
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function structuredData(array $blocks): array
|
||||
{
|
||||
$questions = [];
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
if ($block['type'] !== 'faq') {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ((array) ($block['data']['items'] ?? []) as $item) {
|
||||
if (($item['question'] ?? '') !== '' && ($item['answer'] ?? '') !== '') {
|
||||
$questions[] = ['@type' => 'Question', 'name' => $item['question'], 'acceptedAnswer' => ['@type' => 'Answer', 'text' => $item['answer']]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $questions === [] ? [] : [['@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $questions]];
|
||||
}
|
||||
|
||||
/**
|
||||
* The records of the list a block shows: the active ones, as many as the block asks. Null when the list does not exist (or its feature is off).
|
||||
* On the page of a record the block may show only those that belong to it (`match_list` equals `match_record`, both fields the definitions
|
||||
* know, `id` included) and leave the record itself out; a filter that names a field that does not exist shows nothing, not everything.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param ?array{resource: string, row: array{id: mixed, values: array<string, mixed>}} $context
|
||||
* @return ?list<array<string, mixed>>
|
||||
*/
|
||||
private static function items(array $data, ?array $context = null): ?array
|
||||
{
|
||||
$resource = Resources::find((string) ($data['source'] ?? ''));
|
||||
|
||||
if ($resource === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$count = max(1, min(24, (int) ($data['count'] ?? 3) ?: 3));
|
||||
$listField = trim((string) ($data['match_list'] ?? ''));
|
||||
$recordField = trim((string) ($data['match_record'] ?? ''));
|
||||
$filtered = $listField !== '' || $recordField !== '';
|
||||
$wanted = null;
|
||||
|
||||
if ($filtered) {
|
||||
$values = $context === null ? [] : ['id' => $context['row']['id']] + $context['row']['values'];
|
||||
$known = ($listField === 'id' || isset($resource['fields'][$listField])) && array_key_exists($recordField, $values);
|
||||
$wanted = $known && is_scalar($values[$recordField]) && (string) $values[$recordField] !== '' ? (string) $values[$recordField] : false;
|
||||
}
|
||||
|
||||
if ($wanted === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$items = [];
|
||||
|
||||
foreach (Resources::query($resource)->limit(200)->get() as $model) {
|
||||
$row = Resources::row($resource, $model);
|
||||
|
||||
if (! ($row['values']['is_active'] ?? true) || count($items) >= $count) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($context !== null && ($data['skip_this'] ?? true) && $resource['key'] === $context['resource'] && (string) $row['id'] === (string) $context['row']['id']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($wanted !== null) {
|
||||
$mine = $listField === 'id' ? $row['id'] : ($row['values'][$listField] ?? null);
|
||||
|
||||
if (! is_scalar($mine) || (string) $mine !== $wanted) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$items[] = ['id' => $row['id']] + $row['values'];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $type */
|
||||
private static function style(array $type, array $input): array
|
||||
{
|
||||
$tokens = self::tokens();
|
||||
$out = [];
|
||||
|
||||
foreach ($type['style'] as $name) {
|
||||
$value = $input[$name] ?? null;
|
||||
$out[$name] = is_string($value) && isset($tokens[$name][$value]) ? $value : (string) array_key_first($tokens[$name]);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function id(mixed $given): string
|
||||
{
|
||||
return is_string($given) && preg_match('/^[0-9a-z]{26}$/i', $given) === 1 ? strtolower($given) : strtolower((string) Str::ulid());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Blocks;
|
||||
|
||||
/**
|
||||
* The block types the package ships. A site adds its own in `manager.blocks.types` (or with `Blocks::register()`) and can
|
||||
* replace one by using the same key. Fields use the types of `Support\Fields`; `style` names options from `manager.blocks.tokens`.
|
||||
* Labels are English; `simple` is the plain wording of the simple face.
|
||||
*/
|
||||
final class CoreTypes
|
||||
{
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
public static function all(): array
|
||||
{
|
||||
$buttons = ['type' => 'repeater', 'items' => [
|
||||
'label' => ['type' => 'text', 'label' => 'Text'],
|
||||
'url' => ['type' => 'url', 'label' => 'Address'],
|
||||
'style' => ['type' => 'select', 'label' => 'Look', 'options' => ['primary' => 'Main', 'secondary' => 'Second']],
|
||||
]];
|
||||
|
||||
return [
|
||||
'hero' => ['label' => 'Hero', 'group' => 'Opening', 'icon' => 'hero', 'simple' => ['label' => 'The big opening of the page'], 'style' => ['height', 'align'], 'fields' => [
|
||||
'eyebrow' => ['type' => 'text', 'label' => 'Line above the title'],
|
||||
'title' => ['type' => 'text', 'label' => 'Title', 'required' => true, 'simple' => ['label' => 'The big title']],
|
||||
'intro' => ['type' => 'textarea', 'label' => 'Text', 'simple' => ['label' => 'A few words under the title']],
|
||||
'photo' => ['type' => 'media', 'label' => 'Photo', 'help' => 'Wide (landscape), at least 1600 pixels across; it is cut to fit, so keep what matters in the middle.', 'simple' => ['help' => 'Hold your phone sideways when you take it, and keep what matters in the middle: the edges can be cut off.']],
|
||||
'roles' => ['type' => 'list', 'label' => 'Words that follow each other', 'advanced' => true],
|
||||
'buttons' => ['label' => 'Buttons'] + $buttons,
|
||||
]],
|
||||
'page_title' => ['label' => 'Page title', 'group' => 'Opening', 'icon' => 'title', 'simple' => ['label' => 'A title for the page'], 'style' => ['align'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title', 'required' => true],
|
||||
'intro' => ['type' => 'markdown', 'label' => 'Text under the title'],
|
||||
]],
|
||||
'rich_text' => ['label' => 'Text', 'group' => 'Content', 'icon' => 'text', 'simple' => ['label' => 'A piece of text'], 'style' => ['width'], 'fields' => [
|
||||
'body' => ['type' => 'markdown', 'label' => 'Text', 'required' => true],
|
||||
]],
|
||||
'text_media' => ['label' => 'Text with picture', 'group' => 'Content', 'icon' => 'image-text', 'simple' => ['label' => 'A text with a picture next to it'], 'style' => ['side', 'background'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'body' => ['type' => 'markdown', 'label' => 'Text'],
|
||||
'photo' => ['type' => 'media', 'label' => 'Picture', 'help' => 'Landscape or square, at least 1000 pixels across.', 'simple' => ['help' => 'Any photo will do, as long as it is sharp.']],
|
||||
'caption' => ['type' => 'text', 'label' => 'Caption', 'advanced' => true],
|
||||
'points' => ['type' => 'list', 'label' => 'Points', 'advanced' => true],
|
||||
]],
|
||||
'image' => ['label' => 'Picture', 'group' => 'Content', 'icon' => 'image', 'simple' => ['label' => 'One picture'], 'style' => ['width'], 'fields' => [
|
||||
'photo' => ['type' => 'media', 'label' => 'Picture', 'required' => true, 'help' => 'At least 1200 pixels across; it is shown as wide as the block allows.', 'simple' => ['help' => 'Any sharp photo will do. A photo from your phone is fine.']],
|
||||
'caption' => ['type' => 'text', 'label' => 'Caption'],
|
||||
]],
|
||||
'points_box' => ['label' => 'Box with points', 'group' => 'Content', 'icon' => 'list', 'simple' => ['label' => 'A box with a short list'], 'style' => ['background'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'points' => ['type' => 'list', 'label' => 'Points'],
|
||||
]],
|
||||
'gallery' => ['label' => 'Gallery', 'group' => 'Content', 'icon' => 'gallery', 'simple' => ['label' => 'Several pictures'], 'style' => ['columns'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'photos' => ['type' => 'media_list', 'label' => 'Pictures', 'help' => 'At least 800 pixels across each; they are shown as squares or in a grid, so keep what matters in the middle.', 'simple' => ['help' => 'Pick as many as you like, in one go. The first one comes first on the page.']],
|
||||
]],
|
||||
'before_after' => ['label' => 'Before and after', 'group' => 'Content', 'icon' => 'compare', 'simple' => ['label' => 'Two photos: before and after'], 'fields' => [
|
||||
'before' => ['type' => 'media', 'label' => 'Before', 'help' => 'Take both from the same spot and the same side, so they can be compared.', 'simple' => ['help' => 'Take both photos from the same spot, then they fit together.']],
|
||||
'after' => ['type' => 'media', 'label' => 'After', 'help' => 'The same size and angle as the photo before.', 'simple' => ['help' => 'The same spot as the photo before.']],
|
||||
]],
|
||||
'quote' => ['label' => 'Quote', 'group' => 'Content', 'icon' => 'quote', 'simple' => ['label' => 'What someone said about you'], 'fields' => [
|
||||
'quote' => ['type' => 'textarea', 'label' => 'Quote', 'required' => true],
|
||||
'name' => ['type' => 'text', 'label' => 'Name'],
|
||||
'role' => ['type' => 'text', 'label' => 'Place or function'],
|
||||
]],
|
||||
'stats' => ['label' => 'Numbers', 'group' => 'Content', 'icon' => 'stats', 'simple' => ['label' => 'A few big numbers'], 'fields' => [
|
||||
'items' => ['type' => 'repeater', 'label' => 'Numbers', 'items' => ['value' => ['type' => 'number', 'label' => 'Number'], 'suffix' => ['type' => 'text', 'label' => 'After the number'], 'label' => ['type' => 'text', 'label' => 'What it is']]],
|
||||
]],
|
||||
'chips' => ['label' => 'Tags', 'group' => 'Content', 'icon' => 'tags', 'simple' => ['label' => 'A row of short words'], 'fields' => [
|
||||
'items' => ['type' => 'list', 'label' => 'Tags'],
|
||||
]],
|
||||
'faq' => ['label' => 'Questions and answers', 'group' => 'Content', 'icon' => 'faq', 'simple' => ['label' => 'Questions and answers'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'items' => ['type' => 'repeater', 'label' => 'Questions', 'items' => ['question' => ['type' => 'text', 'label' => 'Question'], 'answer' => ['type' => 'textarea', 'label' => 'Answer']]],
|
||||
]],
|
||||
'cards' => ['label' => 'Cards from a list', 'group' => 'From lists', 'icon' => 'cards', 'simple' => ['label' => 'Your services, projects or reviews'], 'style' => ['layout', 'columns', 'background'], 'resolves' => 'list', 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'eyebrow' => ['type' => 'text', 'label' => 'Line above the title', 'advanced' => true],
|
||||
'source' => ['type' => 'select', 'label' => 'Which list', 'required' => true, 'options' => []],
|
||||
'count' => ['type' => 'number', 'label' => 'How many', 'default' => 3],
|
||||
'match_list' => ['type' => 'text', 'label' => 'Only those whose field …', 'advanced' => true, 'help' => 'On the page of a record: the field of this list that points at the record, for example service_id. Leave empty to show them all.'],
|
||||
'match_record' => ['type' => 'text', 'label' => '… equals this field of the record', 'advanced' => true, 'help' => 'The field of the record it has to equal; id is the number of the record itself. Without one, nothing is shown when a field above is filled in.'],
|
||||
'skip_this' => ['type' => 'toggle', 'label' => 'Leave out the record itself', 'advanced' => true, 'default' => true],
|
||||
'button_label' => ['type' => 'text', 'label' => 'Text of the button', 'advanced' => true],
|
||||
'button_url' => ['type' => 'url', 'label' => 'Address of the button', 'advanced' => true],
|
||||
]],
|
||||
'cta' => ['label' => 'Call to action', 'group' => 'Action', 'icon' => 'cta', 'simple' => ['label' => 'A banner that asks the visitor to act'], 'style' => ['background'], 'fields' => [
|
||||
'title' => ['type' => 'text', 'label' => 'Title', 'required' => true],
|
||||
'text' => ['type' => 'textarea', 'label' => 'Text'],
|
||||
'buttons' => ['label' => 'Buttons'] + $buttons,
|
||||
'show_contact' => ['type' => 'toggle', 'label' => 'Show the phone and WhatsApp buttons', 'default' => true],
|
||||
]],
|
||||
'form' => ['label' => 'Request form', 'group' => 'Action', 'icon' => 'form', 'simple' => ['label' => 'A form for visitors'], 'feature' => 'leads', 'fields' => [
|
||||
'form' => ['type' => 'select', 'label' => 'Which form', 'required' => true, 'options' => ['callback' => 'Call me back', 'question' => 'A question', 'quote' => 'A quote', 'contact' => 'A message']],
|
||||
'title' => ['type' => 'text', 'label' => 'Title'],
|
||||
'text' => ['type' => 'textarea', 'label' => 'Text'],
|
||||
]],
|
||||
'divider' => ['label' => 'Line', 'group' => 'Layout', 'icon' => 'divider', 'simple' => ['label' => 'A line between two parts'], 'fields' => []],
|
||||
'spacer' => ['label' => 'Space', 'group' => 'Layout', 'icon' => 'spacer', 'simple' => ['label' => 'Some empty room'], 'style' => ['spacing'], 'fields' => []],
|
||||
];
|
||||
}
|
||||
|
||||
/** The choices of the style options a type can name; a site replaces or adds some in `manager.blocks.tokens`. */
|
||||
public static function tokens(): array
|
||||
{
|
||||
return [
|
||||
'background' => ['none' => 'None', 'light' => 'Light', 'dark' => 'Dark', 'brand' => 'Brand colour'],
|
||||
'width' => ['normal' => 'Normal', 'wide' => 'Wide', 'full' => 'Full width'],
|
||||
'spacing' => ['s' => 'Small', 'm' => 'Medium', 'l' => 'Large'],
|
||||
'align' => ['left' => 'Left', 'center' => 'Centred'],
|
||||
'height' => ['normal' => 'Normal', 'tall' => 'Tall'],
|
||||
'side' => ['right' => 'Picture on the right', 'left' => 'Picture on the left'],
|
||||
'columns' => ['2' => '2', '3' => '3', '4' => '4'],
|
||||
'layout' => ['cards' => 'Cards', 'tiles' => 'Tiles', 'list' => 'List'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* The releases of the site, read from its CHANGELOG.md: a heading per release (`## v0.1.0 - 2026-12-02`), and under it either
|
||||
* a line per change or a heading per kind of change (`### Features`) with a line per change.
|
||||
*/
|
||||
final class Changelog
|
||||
{
|
||||
/**
|
||||
* Newest first, as in the file.
|
||||
*
|
||||
* @return list<array{version: string, date: ?string, sections: list<array{title: string, items: list<string>}>}>
|
||||
*/
|
||||
public static function releases(?string $path = null, int $limit = 20): array
|
||||
{
|
||||
$path ??= (string) (config('manager.updates.changelog') ?: base_path('CHANGELOG.md'));
|
||||
|
||||
if (! is_file($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$releases = [];
|
||||
|
||||
foreach (preg_split('/\R/', (string) file_get_contents($path)) ?: [] as $line) {
|
||||
$line = rtrim($line);
|
||||
|
||||
if (preg_match('/^##\s+\[?(v?\d+\.\d+\.\d+[^\s\]]*)\]?(?:\s+-\s+(\d{4}-\d{2}-\d{2}))?/', $line, $match) === 1) {
|
||||
$releases[] = ['version' => $match[1], 'date' => $match[2] ?? null, 'sections' => []];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($releases === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$last = count($releases) - 1;
|
||||
|
||||
if (preg_match('/^###\s+(.+)$/', $line, $match) === 1) {
|
||||
$releases[$last]['sections'][] = ['title' => trim($match[1]), 'items' => []];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^[*-]\s+(.+)$/', $line, $match) === 1) {
|
||||
// A line directly under the release, without a heading of its own kind, goes in a section without a title.
|
||||
if ($releases[$last]['sections'] === []) {
|
||||
$releases[$last]['sections'][] = ['title' => '', 'items' => []];
|
||||
}
|
||||
|
||||
$section = count($releases[$last]['sections']) - 1;
|
||||
$releases[$last]['sections'][$section]['items'][] = self::plain($match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return array_slice($releases, 0, max(1, $limit));
|
||||
}
|
||||
|
||||
/** A line without its Markdown and without the commit it came from: "(1a2b3c4)" at the end. */
|
||||
private static function plain(string $line): string
|
||||
{
|
||||
$line = (string) preg_replace('/\s*\(\[?[0-9a-f]{7,40}\]?(?:\([^)]*\))?\)\s*$/', '', $line);
|
||||
$line = (string) preg_replace('/\[([^\]]+)\]\([^)]*\)/', '$1', $line);
|
||||
|
||||
return trim(str_replace(['**', '`'], '', $line));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Costs;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use IriksIT\Manager\Models\WorkCost;
|
||||
use IriksIT\Manager\Support\IriksStorage\Client;
|
||||
|
||||
/**
|
||||
* The pieces of work on the site with the tokens that went into each, read from the table of the site's `TOKENS.md`, and priced in euros.
|
||||
*
|
||||
* A row of the table: date, what was made, the release it is in (empty while it is not released), the model, the number of answers
|
||||
* of the model, four kinds of tokens (written, read for the first time, stored in the cache, read again from the cache) and, as an
|
||||
* optional last cell, the hours that were worked on it.
|
||||
*
|
||||
* A row is priced once and the answer is kept in the table `work_costs`, because the price of a day in the past does not change. Who
|
||||
* prices it, in this order: a class of the site (`manager.costs.pricer`, invokable, gets the rows to price and returns the costs by
|
||||
* reference), the IriksIT API (when `manager.media.iriksit` is set and `manager.costs.use_api` is on: it keeps the price lists of the
|
||||
* models and the euro rates with their history), and last the fixed rates of `manager.costs.rates`. `priced_by` of a row says which.
|
||||
*
|
||||
* Three costs are kept apart: the tokens of the AI model (`eur`), the work itself (`work_eur`, the hours at the hourly rate) and hosting
|
||||
* (a fixed amount per year).
|
||||
*/
|
||||
final class Ledger
|
||||
{
|
||||
/**
|
||||
* @return list<array{date: string, name: string, version: string|null, model: string, steps: int, output: int, input: int, cache_write: int, cache_read: int, tokens: int, usd: float|null, eur: float|null, priced_by: string|null, usd_to_eur: float|null, hours: float|null, work_eur: float|null}>
|
||||
*/
|
||||
public function items(): array
|
||||
{
|
||||
$items = $this->rows();
|
||||
$costs = $this->kept($items);
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
$cost = $costs['row-'.$index] ?? null;
|
||||
|
||||
if ($cost !== null) {
|
||||
$items[$index] = ['usd' => round($cost['usd'], 4), 'eur' => round($cost['eur'], 2), 'priced_by' => 'service', 'usd_to_eur' => round(1 / $cost['usd_per_eur'], 4)] + $item;
|
||||
}
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/** The rows of the file, priced with the fixed rates. */
|
||||
private function rows(): array
|
||||
{
|
||||
$path = config('manager.costs.ledger') ?: base_path('TOKENS.md');
|
||||
|
||||
if (! is_string($path) || ! is_file($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$items = [];
|
||||
$inTable = false;
|
||||
|
||||
foreach (preg_split('/\R/', (string) file_get_contents($path)) ?: [] as $line) {
|
||||
$line = trim($line);
|
||||
|
||||
if (! str_starts_with($line, '|')) {
|
||||
$inTable = false;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$cells = array_map(trim(...), explode('|', trim($line, '|')));
|
||||
|
||||
// Nine cells, or ten with the hours that were worked as the last one.
|
||||
if (in_array(count($cells), [9, 10], true) && strcasecmp($cells[0], 'Datum') === 0) {
|
||||
$inTable = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// A row of this table starts with a date; the line of dashes under the header does not.
|
||||
if (! $inTable || ! in_array(count($cells), [9, 10], true) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $cells[0]) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$item = [
|
||||
'date' => $cells[0],
|
||||
'name' => $cells[1],
|
||||
'version' => $cells[2] !== '' ? $cells[2] : null,
|
||||
'model' => $cells[3],
|
||||
'steps' => self::number($cells[4]),
|
||||
'output' => self::number($cells[5]),
|
||||
'input' => self::number($cells[6]),
|
||||
'cache_write' => self::number($cells[7]),
|
||||
'cache_read' => self::number($cells[8]),
|
||||
];
|
||||
$item['tokens'] = $item['output'] + $item['input'] + $item['cache_write'] + $item['cache_read'];
|
||||
// A row of work without the model (hours only) costs nothing in tokens.
|
||||
$item['usd'] = $item['tokens'] === 0 ? 0.0 : $this->usd($item);
|
||||
$item['eur'] = $item['usd'] !== null && $this->rate() > 0 ? round($item['usd'] * $this->rate(), 2) : null;
|
||||
$item['priced_by'] = $item['eur'] !== null ? 'config' : null;
|
||||
$item['usd_to_eur'] = $item['eur'] !== null ? $this->rate() : null;
|
||||
$item['hours'] = self::hours($cells[9] ?? '');
|
||||
$item['work_eur'] = $item['hours'] !== null ? round($item['hours'] * $this->hourlyRate(), 2) : null;
|
||||
|
||||
$items[] = $item;
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the tokens of the rows cost, by the place of the row in the list ("row-0"), from the table of kept prices and, for the
|
||||
* rows that are not in it, from the pricer of the site or the API. Only rows without a kept price are asked, all in one request;
|
||||
* a visit to the screen of a site whose rows are all priced asks nothing. When nobody can say, that is remembered for ten minutes,
|
||||
* so a server that is down is not asked again by every visit.
|
||||
*
|
||||
* @param list<array<string, mixed>> $items
|
||||
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>
|
||||
*/
|
||||
private function kept(array $items): array
|
||||
{
|
||||
$prints = [];
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
// A row without tokens costs nothing and needs no price.
|
||||
if ($item['tokens'] > 0) {
|
||||
$prints[$index] = self::fingerprint($item);
|
||||
}
|
||||
}
|
||||
|
||||
if ($prints === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$costs = [];
|
||||
$stored = WorkCost::query()->whereIn('fingerprint', array_values($prints))->get()->keyBy('fingerprint');
|
||||
|
||||
foreach ($prints as $index => $print) {
|
||||
$kept = $stored->get($print);
|
||||
|
||||
if ($kept instanceof WorkCost) {
|
||||
$costs['row-'.$index] = ['usd' => (float) $kept->usd, 'eur' => (float) $kept->eur, 'usd_per_eur' => (float) $kept->usd_per_eur];
|
||||
}
|
||||
}
|
||||
|
||||
$missing = array_filter($prints, fn (string $print) => ! $stored->has($print));
|
||||
|
||||
if ($missing === []) {
|
||||
return $costs;
|
||||
}
|
||||
|
||||
$ask = [];
|
||||
|
||||
foreach ($missing as $index => $print) {
|
||||
$ask[] = [
|
||||
'reference' => 'row-'.$index,
|
||||
'model' => $items[$index]['model'],
|
||||
'date' => $items[$index]['date'],
|
||||
// The sessions that wrote the table used the one-hour cache.
|
||||
'tokens' => ['output' => $items[$index]['output'], 'input' => $items[$index]['input'], 'cache_write_1h' => $items[$index]['cache_write'], 'cache_read' => $items[$index]['cache_read']],
|
||||
];
|
||||
}
|
||||
|
||||
$failed = 'manager.costs.failed:'.hash('sha256', (string) json_encode($ask));
|
||||
|
||||
if (Cache::has($failed)) {
|
||||
return $costs;
|
||||
}
|
||||
|
||||
$answer = $this->ask($ask);
|
||||
|
||||
if ($answer === null) {
|
||||
Cache::put($failed, true, now()->addMinutes(10));
|
||||
|
||||
return $costs;
|
||||
}
|
||||
|
||||
foreach ($missing as $index => $print) {
|
||||
$cost = $answer['row-'.$index] ?? null;
|
||||
|
||||
if ($cost === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
WorkCost::query()->updateOrCreate(['fingerprint' => $print], [
|
||||
'date' => $items[$index]['date'],
|
||||
'name' => mb_substr($items[$index]['name'], 0, 255),
|
||||
'version' => $items[$index]['version'],
|
||||
'model' => $items[$index]['model'],
|
||||
'usd' => $cost['usd'],
|
||||
'eur' => $cost['eur'],
|
||||
'usd_per_eur' => $cost['usd_per_eur'],
|
||||
'priced_at' => now(),
|
||||
]);
|
||||
$costs['row-'.$index] = $cost;
|
||||
}
|
||||
|
||||
// What nobody had a price for (a model it does not know) is not asked again for six hours.
|
||||
$left = array_values(array_filter($ask, fn (array $row) => ! isset($answer[$row['reference']])));
|
||||
|
||||
if ($left !== []) {
|
||||
Cache::put('manager.costs.failed:'.hash('sha256', (string) json_encode($left)), true, now()->addHours(6));
|
||||
}
|
||||
|
||||
return $costs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $ask
|
||||
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>|null
|
||||
*/
|
||||
private function ask(array $ask): ?array
|
||||
{
|
||||
$pricer = config('manager.costs.pricer');
|
||||
|
||||
if (is_string($pricer) && $pricer !== '' && (class_exists($pricer) || app()->bound($pricer))) {
|
||||
$answer = app($pricer)($ask);
|
||||
|
||||
return is_array($answer) ? $answer : null;
|
||||
}
|
||||
|
||||
if (! config('manager.costs.use_api', true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$client = new Client((array) config('manager.media.iriksit', []));
|
||||
|
||||
return $client->isConfigured() ? $client->tokenCosts($ask) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes a row the row it is, for its price: the day, the model and the tokens.
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
*/
|
||||
private static function fingerprint(array $item): string
|
||||
{
|
||||
return hash('sha256', implode('|', [$item['date'], $item['model'], $item['output'], $item['input'], $item['cache_write'], $item['cache_read']]));
|
||||
}
|
||||
|
||||
/** Euros for an hour of work: a cost of its own, apart from what the AI model costs. */
|
||||
public function hourlyRate(): float
|
||||
{
|
||||
$rate = config('manager.costs.hourly_rate');
|
||||
|
||||
return is_numeric($rate) ? (float) $rate : 0.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* What hosting has cost until a day: the yearly amount once for every year that has begun since its first day, and nothing before.
|
||||
*
|
||||
* @return array{per_year: float, from: string|null, years: int, eur: float}
|
||||
*/
|
||||
public function hosting(?CarbonImmutable $on = null): array
|
||||
{
|
||||
$perYear = config('manager.costs.hosting.per_year');
|
||||
$from = config('manager.costs.hosting.from');
|
||||
$perYear = is_numeric($perYear) ? (float) $perYear : 0.0;
|
||||
$on ??= CarbonImmutable::today();
|
||||
|
||||
if (! is_string($from) || $from === '') {
|
||||
return ['per_year' => $perYear, 'from' => null, 'years' => 0, 'eur' => 0.0];
|
||||
}
|
||||
|
||||
$start = CarbonImmutable::parse($from)->startOfDay();
|
||||
$years = $on->lt($start) ? 0 : (int) floor($start->diffInYears($on)) + 1;
|
||||
|
||||
return ['per_year' => $perYear, 'from' => $start->toDateString(), 'years' => $years, 'eur' => round($years * $perYear, 2)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The discount on the work and the AI costs: which share, and until which day (rows dated on or after that day get none).
|
||||
* Null when there is no discount. Hosting is not part of it.
|
||||
*
|
||||
* @return array{percent: float, until: string}|null
|
||||
*/
|
||||
public function discount(): ?array
|
||||
{
|
||||
$percent = config('manager.costs.discount.percent');
|
||||
$until = config('manager.costs.discount.until');
|
||||
|
||||
if (! is_numeric($percent) || (float) $percent <= 0 || ! is_string($until) || $until === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['percent' => min(100.0, (float) $percent), 'until' => CarbonImmutable::parse($until)->toDateString()];
|
||||
}
|
||||
|
||||
/**
|
||||
* What of a row is not charged: the discount on its work and its AI costs.
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
*/
|
||||
public function discountOn(array $item): float
|
||||
{
|
||||
$discount = $this->discount();
|
||||
|
||||
if ($discount === null || $item['date'] >= $discount['until']) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
return round((($item['work_eur'] ?? 0.0) + ($item['eur'] ?? 0.0)) * $discount['percent'] / 100, 2);
|
||||
}
|
||||
|
||||
/** Euros for one US dollar, for the rows that are priced with the fixed rates; 0 when the site gave none. */
|
||||
public function rate(): float
|
||||
{
|
||||
$rate = config('manager.costs.usd_to_eur');
|
||||
|
||||
return is_numeric($rate) ? (float) $rate : 0.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a row costs at the fixed price list, or null when the model has no prices there.
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
*/
|
||||
private function usd(array $item): ?float
|
||||
{
|
||||
$rates = config('manager.costs.rates.'.$item['model']);
|
||||
|
||||
if (! is_array($rates)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$usd = 0.0;
|
||||
|
||||
foreach (['output', 'input', 'cache_write', 'cache_read'] as $kind) {
|
||||
$price = $rates[$kind] ?? null;
|
||||
|
||||
if (! is_numeric($price)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$usd += $item[$kind] * (float) $price / 1_000_000;
|
||||
}
|
||||
|
||||
return round($usd, 4);
|
||||
}
|
||||
|
||||
/** "1,25" or "1.25" hours as it is written in the file; an empty cell is not known. */
|
||||
private static function hours(string $cell): ?float
|
||||
{
|
||||
$cell = str_replace(',', '.', trim($cell));
|
||||
|
||||
return is_numeric($cell) && (float) $cell >= 0 ? round((float) $cell, 2) : null;
|
||||
}
|
||||
|
||||
/** "1.234.567" as it is written in the file. */
|
||||
private static function number(string $cell): int
|
||||
{
|
||||
return (int) preg_replace('/\D/', '', $cell);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* The features of a site that can be switched on and off from the settings screen (config `manager.features`): services, projects,
|
||||
* reviews, requests, a contact form. A feature is one switch that the whole site follows:
|
||||
*
|
||||
* 'features' => ['services' => ['label' => 'Services', 'enabled' => true, 'env' => 'SITE_SERVICES', 'hint' => 'The page with what you offer']]
|
||||
*
|
||||
* - the manager: a `resources` entry with `'feature' => 'services'` is left out when it is off (menu, permissions, screens, routes),
|
||||
* - the public site: `Features::on('services')`, the route middleware `manager.feature:services` (a 404 when off), the Blade
|
||||
* condition `@feature('services') … @endfeature`, and `Features::flags()` for what a page needs to know (links, sitemap).
|
||||
*
|
||||
* Off hides, it does not delete: the data stays where it is and comes back when the switch goes on again. The value lives at
|
||||
* `manager.features.<key>.enabled`, which is also the path the settings screen changes.
|
||||
*/
|
||||
final class Features
|
||||
{
|
||||
/** @return array<string, array{key: string, label: string, hint: ?string, enabled: bool, env: ?string}> */
|
||||
public static function all(): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ((array) config('manager.features', []) as $key => $definition) {
|
||||
if (! is_string($key) || preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$definition = is_array($definition) ? $definition : ['enabled' => (bool) $definition];
|
||||
$env = $definition['env'] ?? null;
|
||||
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null,
|
||||
'enabled' => filter_var($definition['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
||||
'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null,
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Whether a feature is on. A name that is not a feature is off: nothing shows up that nobody declared. */
|
||||
public static function on(string $key): bool
|
||||
{
|
||||
return (self::all()[$key]['enabled'] ?? false) === true;
|
||||
}
|
||||
|
||||
/** @return array<string, bool> every feature and whether it is on, to hand to a page */
|
||||
public static function flags(): array
|
||||
{
|
||||
return array_map(fn (array $feature) => $feature['enabled'], self::all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Field definitions: what a page, or any other record a site manages without code of its own, is made of.
|
||||
* One definition drives the form of the screens, the validation and the cleaning of what is stored, so a
|
||||
* field is declared once:
|
||||
*
|
||||
* 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text', 'help' => 'One line.', 'max' => 120]
|
||||
*
|
||||
* Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item
|
||||
* per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`,
|
||||
* `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label, or `source`: `['model' => Service::class, 'label' => 'title', 'value' => 'id']`
|
||||
* for the rows of a table of the site). More: `slug` (an address part; `from` names the field it is made of when it is left empty), `list` (a list of short texts,
|
||||
* one per line), `media_list` (a list of pictures from the media library, a gallery) and `repeater` (a list of items that each have the fields of `items`, for example
|
||||
* questions and answers). The last three are stored as arrays. `required`, `default` and
|
||||
* `rules` (extra Laravel rules) are optional on every type. `help` is a line of explanation under the field; `advanced`
|
||||
* hides the field in the simple face of the manager (it keeps its value). `simple` gives the simple face its own words,
|
||||
* for someone who is not a webmaster: `'simple' => ['label' => 'Your phone number', 'help' => 'As you want it to be read.']`; a part
|
||||
* left out falls back to `label` / `help`.
|
||||
*/
|
||||
final class Fields
|
||||
{
|
||||
public const TYPES = ['text', 'textarea', 'markdown', 'lines', 'media', 'url', 'number', 'date', 'toggle', 'select', 'slug', 'list', 'media_list', 'repeater'];
|
||||
|
||||
/** What a repeater item may be made of. */
|
||||
private const ITEM_TYPES = ['text', 'textarea', 'url', 'media'];
|
||||
|
||||
private const LENGTHS = ['text' => 255, 'textarea' => 20000, 'markdown' => 100000, 'lines' => 10000, 'media' => 2048, 'url' => 2048, 'date' => 40, 'select' => 255, 'slug' => 120];
|
||||
|
||||
/**
|
||||
* The definitions in one shape, with a key, a label and a known type; what is wrong is dropped.
|
||||
*
|
||||
* @param array<array-key, mixed> $fields key => definition
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, simple_label: ?string, simple_help: ?string, advanced: bool, required: bool, default: mixed, options: array<string, string>, source: ?array{model: class-string<Eloquent>, label: string, value: string}, from: ?string, items: array<string, array<string, mixed>>, max: ?int, rules: list<mixed>}>
|
||||
*/
|
||||
public static function normalize(array $fields): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,59}$/', $key) || ! is_array($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = in_array($field['type'] ?? 'text', self::TYPES, true) ? ($field['type'] ?? 'text') : 'text';
|
||||
$options = [];
|
||||
|
||||
$given = (array) ($field['options'] ?? []);
|
||||
|
||||
foreach ($given as $value => $label) {
|
||||
$options[(string) (array_is_list($given) ? $label : $value)] = (string) $label;
|
||||
}
|
||||
|
||||
$source = self::source($field['source'] ?? null);
|
||||
|
||||
if ($type === 'select' && $options === [] && $source === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items = $type === 'repeater' ? self::normalizeItems((array) ($field['items'] ?? [])) : [];
|
||||
|
||||
if ($type === 'repeater' && $items === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'type' => $type,
|
||||
'help' => isset($field['help']) ? (string) $field['help'] : null,
|
||||
'simple_label' => self::simpleText($field, 'label'),
|
||||
'simple_help' => self::simpleText($field, 'help'),
|
||||
'advanced' => (bool) ($field['advanced'] ?? false),
|
||||
'required' => (bool) ($field['required'] ?? false),
|
||||
'default' => $field['default'] ?? self::empty($type),
|
||||
'options' => $options,
|
||||
'source' => $source,
|
||||
'from' => $type === 'slug' && isset($field['from']) ? (string) $field['from'] : null,
|
||||
'items' => $items,
|
||||
'max' => isset($field['max']) ? max(1, (int) $field['max']) : null,
|
||||
'rules' => array_values((array) ($field['rules'] ?? [])),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Laravel rules for the values, keyed `<prefix><key>`.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @return array<string, list<mixed>>
|
||||
*/
|
||||
public static function rules(array $fields, string $prefix = ''): array
|
||||
{
|
||||
$rules = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$type = $field['type'];
|
||||
$max = $field['max'] ?? self::LENGTHS[$type] ?? null;
|
||||
$presence = $field['required'] ? 'required' : 'nullable';
|
||||
|
||||
$rules[$prefix.$key] = [$presence, ...match ($type) {
|
||||
'toggle' => ['boolean'],
|
||||
'number' => ['numeric'],
|
||||
'date' => ['date'],
|
||||
'select' => $field['source'] === null ? ['string', Rule::in(array_keys($field['options']))] : [Rule::in(array_keys(self::optionsOf($field)))],
|
||||
'media', 'url' => ['string', 'max:'.$max, 'regex:'.self::ADDRESS],
|
||||
'slug' => ['string', 'max:'.$max, 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'],
|
||||
'list' => ['array', 'max:100'],
|
||||
'media_list' => ['array', 'max:50'],
|
||||
'repeater' => ['array', 'max:50'],
|
||||
default => ['string', 'max:'.$max],
|
||||
}, ...$field['rules']];
|
||||
|
||||
if ($type === 'list') {
|
||||
$rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:500'];
|
||||
} elseif ($type === 'media_list') {
|
||||
$rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:2048', 'regex:'.self::ADDRESS];
|
||||
} elseif ($type === 'repeater') {
|
||||
foreach (self::rules($field['items']) as $sub => $subRules) {
|
||||
$rules[$prefix.$key.'.*.'.$sub] = $subRules;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** A web address or a path of the site. Never `javascript:` and its kin. */
|
||||
public const ADDRESS = '#^(/(?!/)|https?://)[^\s<>"\']*$#i';
|
||||
|
||||
/**
|
||||
* What is stored: only the known keys, in the type of the field, the default where nothing is given.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function clean(array $fields, array $input): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$value = array_key_exists($key, $input) ? $input[$key] : $field['default'];
|
||||
|
||||
$out[$key] = match ($field['type']) {
|
||||
'toggle' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'number' => $value === null || $value === '' ? null : $value + 0,
|
||||
'select' => $field['source'] !== null && ($value === null || $value === '') ? null : (is_scalar($value) ? trim((string) $value) : ''),
|
||||
'list', 'media_list' => self::strings($value),
|
||||
'repeater' => self::cleanItems($field['items'], $value),
|
||||
default => $value === null ? '' : (is_scalar($value) ? trim((string) $value) : ''),
|
||||
};
|
||||
}
|
||||
|
||||
// An address part that was left empty is made of the field it follows.
|
||||
foreach ($fields as $key => $field) {
|
||||
if ($field['type'] === 'slug' && $out[$key] === '' && $field['from'] !== null && is_string($out[$field['from']] ?? null)) {
|
||||
$out[$key] = Str::slug($out[$field['from']]);
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored values over the defaults, for the screens and for the public site.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @param array<array-key, mixed> $stored
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function values(array $fields, array $stored): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
$out[$key] = array_key_exists($key, $stored) ? $stored[$key] : $field['default'];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The options of a select: the fixed ones, or the rows of the table of the site it is made from (value => label).
|
||||
*
|
||||
* @param array<string, mixed> $field normalized
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function optionsOf(array $field): array
|
||||
{
|
||||
$source = $field['source'] ?? null;
|
||||
|
||||
if ($source === null) {
|
||||
return $field['options'];
|
||||
}
|
||||
|
||||
return $source['model']::query()->orderBy($source['label'])->pluck($source['label'], $source['value'])->mapWithKeys(fn ($label, $value) => [(string) $value => (string) $label])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields with the options of a table of the site filled in, as the screens need them.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $fields normalized
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function described(array $fields): array
|
||||
{
|
||||
return array_values(array_map(fn (array $field) => $field['source'] === null ? $field : [...$field, 'options' => self::optionsOf($field)], $fields));
|
||||
}
|
||||
|
||||
/** @return ?array{model: class-string<Eloquent>, label: string, value: string} */
|
||||
private static function source(mixed $source): ?array
|
||||
{
|
||||
if (! is_array($source) || ! is_string($source['model'] ?? null) || ! is_subclass_of($source['model'], Eloquent::class)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$label = (string) ($source['label'] ?? 'name');
|
||||
$value = (string) ($source['value'] ?? 'id');
|
||||
|
||||
return preg_match('/^[a-z_][a-z0-9_]*$/i', $label.$value) === 1 ? ['model' => $source['model'], 'label' => $label, 'value' => $value] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $items
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private static function normalizeItems(array $items): array
|
||||
{
|
||||
$fields = array_filter(self::normalize($items), fn (array $field) => in_array($field['type'], self::ITEM_TYPES, true));
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* One of the words the simple face has of its own (`simple.label`, `simple.help`), or null.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
*/
|
||||
public static function simpleText(array $definition, string $part): ?string
|
||||
{
|
||||
$text = is_array($definition['simple'] ?? null) ? ($definition['simple'][$part] ?? null) : null;
|
||||
|
||||
return is_string($text) && trim($text) !== '' ? trim($text) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of short texts: an array, or a text with one per line; empty ones are dropped.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function strings(mixed $value): array
|
||||
{
|
||||
$value = is_string($value) ? preg_split('/\R/u', $value) : (array) $value;
|
||||
|
||||
return array_values(array_filter(array_map(fn ($item) => is_scalar($item) ? trim((string) $item) : '', $value ?: []), fn ($item) => $item !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array<string, mixed>> $items normalized
|
||||
* @return list<array<string, string>>
|
||||
*/
|
||||
private static function cleanItems(array $items, mixed $value): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach (is_array($value) ? $value : [] as $item) {
|
||||
$clean = self::clean($items, is_array($item) ? $item : []);
|
||||
|
||||
if (array_filter($clean, fn ($part) => $part !== '') !== []) {
|
||||
$out[] = $clean;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function empty(string $type): mixed
|
||||
{
|
||||
return match ($type) {
|
||||
'toggle' => false,
|
||||
'number' => null,
|
||||
'list', 'media_list', 'repeater' => [],
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* Who draws the pages of the site (config `manager.frontend.mode`, switchable on the settings screen):
|
||||
*
|
||||
* - `site`: the site draws them itself with its own routes and the blocks (Inertia + Vue or Blade). The package adds no public route. The default.
|
||||
* - `package`: the package draws them: every page with blocks answers at `/{slug}` (the home page at `/`) in the Blade layout
|
||||
* `manager.frontend.layout`, as long as no route of the site answers first (it is a fallback route).
|
||||
* - `headless`: nothing is drawn here; the pages are JSON for a frontend elsewhere (the page API is on).
|
||||
*
|
||||
* The page API (`manager.blocks.api.enabled`) and the live preview (`manager.blocks.preview.enabled`) are switches of their own; `headless` implies the API.
|
||||
*/
|
||||
final class Frontend
|
||||
{
|
||||
public const MODES = ['site', 'package', 'headless'];
|
||||
|
||||
public static function mode(): string
|
||||
{
|
||||
$mode = config('manager.frontend.mode', 'site');
|
||||
|
||||
return is_string($mode) && in_array($mode, self::MODES, true) ? $mode : 'site';
|
||||
}
|
||||
|
||||
/** Whether the package draws the public pages. */
|
||||
public static function renders(): bool
|
||||
{
|
||||
return self::mode() === 'package';
|
||||
}
|
||||
|
||||
/** Whether the pages go out as JSON: the headless mode, or the switch of the API on its own. */
|
||||
public static function api(): bool
|
||||
{
|
||||
return self::mode() === 'headless' || (bool) config('manager.blocks.api.enabled', false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadTap;
|
||||
use IriksIT\Manager\Models\Media;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Review;
|
||||
|
||||
/**
|
||||
* Copies the rows of a site's own table into a table of the package, so a site that already has posts,
|
||||
* pages or reviews does not start empty. It only reads the source and never writes to it; running it again
|
||||
* updates the rows it made before (they are found by the `key` columns), so it is safe to repeat.
|
||||
*/
|
||||
final class Importer
|
||||
{
|
||||
/**
|
||||
* What can be imported: the model, the columns the package knows, which of those must have a value, and
|
||||
* the columns that make a row "the same row" when the import runs again.
|
||||
*
|
||||
* @var array<string, array{model: class-string<Eloquent>, columns: list<string>, required: list<string>, key: list<string>}>
|
||||
*/
|
||||
public const TARGETS = [
|
||||
'posts' => [
|
||||
'model' => Post::class,
|
||||
'columns' => ['title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at'],
|
||||
'required' => ['title', 'body'],
|
||||
'key' => ['slug'],
|
||||
],
|
||||
'pages' => [
|
||||
'model' => Page::class,
|
||||
'columns' => ['slug', 'title', 'body', 'is_published'],
|
||||
'required' => ['slug', 'title'],
|
||||
'key' => ['slug'],
|
||||
],
|
||||
// The rows only; the files stay where they are. `disk` and `location` say where (use `--set=disk=iriksit` when the source has no disk column).
|
||||
'media' => [
|
||||
'model' => Media::class,
|
||||
'columns' => ['disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y'],
|
||||
'required' => ['location', 'filename'],
|
||||
'key' => ['disk', 'location'],
|
||||
],
|
||||
// Requests with everything the screening and the follow-up decided. A site that points to a service by id keeps `subject_id` and sets the
|
||||
// `subject` text with `--set=subject=...` or after the import.
|
||||
'leads' => [
|
||||
'model' => Lead::class,
|
||||
'columns' => ['kind', 'folder', 'reasons', 'name', 'phone', 'email', 'prefers', 'about', 'message', 'message_hash', 'answers', 'location', 'subject', 'subject_id', 'page', 'channel', 'source', 'ip', 'opened_at', 'handled_at', 'outcome', 'notes', 'notified_at', 'notify_failed', 'created_at'],
|
||||
'required' => ['kind', 'name', 'created_at'],
|
||||
'key' => ['name', 'kind', 'created_at'],
|
||||
],
|
||||
// How often the phone number and the WhatsApp button were pressed, per day and page.
|
||||
'taps' => [
|
||||
'model' => LeadTap::class,
|
||||
'columns' => ['day', 'kind', 'path', 'taps'],
|
||||
'required' => ['day', 'kind', 'path'],
|
||||
'key' => ['day', 'kind', 'path'],
|
||||
],
|
||||
'reviews' => [
|
||||
'model' => Review::class,
|
||||
'columns' => ['author', 'place', 'rating', 'body', 'is_visible'],
|
||||
'required' => ['author', 'body'],
|
||||
'key' => ['author', 'body'],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, string> $map package column => column of the source table; same name when left out
|
||||
* @param array<string, string> $fixed package column => a value for every row that has none of its own
|
||||
* @return array{created: int, updated: int, skipped: int, problems: list<string>}
|
||||
*/
|
||||
public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null, array $fixed = []): array
|
||||
{
|
||||
$spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS)));
|
||||
|
||||
foreach (array_keys($map) as $column) {
|
||||
if (! in_array($column, $spec['columns'], true)) {
|
||||
throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns']));
|
||||
}
|
||||
}
|
||||
|
||||
$result = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'problems' => []];
|
||||
$query = $source->table($table);
|
||||
$limit !== null && $query->limit($limit);
|
||||
|
||||
foreach ($query->get() as $number => $row) {
|
||||
$row = (array) $row;
|
||||
$values = [];
|
||||
|
||||
foreach ($spec['columns'] as $column) {
|
||||
$from = $map[$column] ?? $column;
|
||||
|
||||
if (array_key_exists($from, $row)) {
|
||||
$values[$column] = $this->convert($column, $row[$from]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($fixed as $column => $value) {
|
||||
if (! in_array($column, $spec['columns'], true)) {
|
||||
throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns']));
|
||||
}
|
||||
|
||||
if (! isset($values[$column]) || $values[$column] === '') {
|
||||
$values[$column] = $this->convert($column, $value);
|
||||
}
|
||||
}
|
||||
|
||||
if ($target === 'media') {
|
||||
foreach (['disk' => config('manager.media.disk'), 'mime_type' => 'application/octet-stream', 'size' => 0] as $column => $default) {
|
||||
if (! isset($values[$column]) || $values[$column] === '') {
|
||||
$values[$column] = $default;
|
||||
}
|
||||
}
|
||||
|
||||
$values['name'] = ($values['name'] ?? '') !== '' ? $values['name'] : pathinfo((string) ($values['filename'] ?? ''), PATHINFO_FILENAME);
|
||||
}
|
||||
|
||||
if ($target === 'posts' || $target === 'pages') {
|
||||
$values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? ''));
|
||||
}
|
||||
|
||||
foreach ($spec['required'] as $column) {
|
||||
if (! isset($values[$column]) || $values[$column] === '') {
|
||||
$result['skipped']++;
|
||||
$result['problems'][] = 'row '.($number + 1).": no value for {$column}";
|
||||
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
|
||||
$key = Arr::only($values, $spec['key']);
|
||||
$model = $spec['model'];
|
||||
$existing = $model::query()->where($key)->first();
|
||||
$existing ? $result['updated']++ : $result['created']++;
|
||||
|
||||
if (! $dry) {
|
||||
$existing ? $existing->update($values) : $model::query()->create($values);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function convert(string $column, mixed $value): mixed
|
||||
{
|
||||
return match ($column) {
|
||||
'tags' => $this->tags($value),
|
||||
'reasons', 'answers', 'notes' => $this->json($value),
|
||||
'notify_failed' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'taps' => max(0, (int) $value),
|
||||
'opened_at', 'handled_at', 'notified_at' => $value === null || $value === '' ? null : $value,
|
||||
'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'size', 'width', 'height' => $value === null || $value === '' ? null : max(0, (int) $value),
|
||||
'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)),
|
||||
'published_at' => $value === null || $value === '' ? null : $value,
|
||||
default => is_string($value) ? trim($value) : $value,
|
||||
};
|
||||
}
|
||||
|
||||
/** @return array<mixed>|null a JSON column as it comes out of another table: text, or already a list */
|
||||
private function json(mixed $value): ?array
|
||||
{
|
||||
if (is_string($value)) {
|
||||
$value = json_decode($value, true);
|
||||
}
|
||||
|
||||
return is_array($value) && $value !== [] ? $value : null;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function tags(mixed $value): array
|
||||
{
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
$value = is_array($decoded) ? $decoded : array_map('trim', explode(',', $value));
|
||||
}
|
||||
|
||||
return array_values(array_filter(array_map(fn ($tag) => is_string($tag) ? trim($tag) : '', (array) $value), fn ($tag) => $tag !== ''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\IriksStorage;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use League\Flysystem\Config;
|
||||
use League\Flysystem\DirectoryAttributes;
|
||||
use League\Flysystem\FileAttributes;
|
||||
use League\Flysystem\FilesystemAdapter;
|
||||
use League\Flysystem\UnableToCopyFile;
|
||||
use League\Flysystem\UnableToCreateDirectory;
|
||||
use League\Flysystem\UnableToDeleteDirectory;
|
||||
use League\Flysystem\UnableToDeleteFile;
|
||||
use League\Flysystem\UnableToMoveFile;
|
||||
use League\Flysystem\UnableToReadFile;
|
||||
use League\Flysystem\UnableToRetrieveMetadata;
|
||||
use League\Flysystem\UnableToSetVisibility;
|
||||
use League\Flysystem\UnableToWriteFile;
|
||||
|
||||
/**
|
||||
* A Laravel disk (`driver` => `iriksit`) whose files live at the IriksIT API. The API knows files by an id of its own, not
|
||||
* by a path, so every path that is written is remembered next to that id (table `storage_files`). A path that has no entry
|
||||
* and no slash is taken for an id itself: that is how media rows that were made by a site's own code (the id as location)
|
||||
* keep working. There are no folders, no visibility and no listing.
|
||||
*/
|
||||
class Adapter implements FilesystemAdapter
|
||||
{
|
||||
public function __construct(private readonly Client $client) {}
|
||||
|
||||
public function fileExists(string $path): bool
|
||||
{
|
||||
$id = $this->id($path);
|
||||
|
||||
if ($id === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->client->details($id) !== null;
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToRetrieveMetadata::create($path, 'exists', $e->getMessage(), $e);
|
||||
}
|
||||
}
|
||||
|
||||
public function directoryExists(string $path): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $path, string $contents, Config $config): void
|
||||
{
|
||||
$stream = fopen('php://temp', 'r+b');
|
||||
fwrite($stream, $contents);
|
||||
rewind($stream);
|
||||
|
||||
try {
|
||||
$this->writeStream($path, $stream, $config);
|
||||
} finally {
|
||||
// The HTTP client closes what it sent itself.
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function writeStream(string $path, $contents, Config $config): void
|
||||
{
|
||||
try {
|
||||
$stored = $this->client->store($contents, basename($path));
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToWriteFile::atLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
DB::table($this->table())->updateOrInsert(['path' => $path], ['remote_id' => $stored['id']]);
|
||||
}
|
||||
|
||||
public function read(string $path): string
|
||||
{
|
||||
$stream = $this->readStream($path);
|
||||
$contents = stream_get_contents($stream);
|
||||
is_resource($stream) && fclose($stream);
|
||||
|
||||
return $contents === false ? throw UnableToReadFile::fromLocation($path) : $contents;
|
||||
}
|
||||
|
||||
public function readStream(string $path)
|
||||
{
|
||||
$id = $this->id($path) ?? throw UnableToReadFile::fromLocation($path, 'There is no such file.');
|
||||
|
||||
try {
|
||||
$body = $this->client->open($id);
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
$stream = fopen('php://temp', 'r+b');
|
||||
while (! $body->eof()) {
|
||||
fwrite($stream, $body->read(1024 * 1024));
|
||||
}
|
||||
$body->close();
|
||||
rewind($stream);
|
||||
|
||||
return $stream;
|
||||
}
|
||||
|
||||
public function delete(string $path): void
|
||||
{
|
||||
$id = $this->id($path);
|
||||
|
||||
if ($id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->client->delete($id);
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToDeleteFile::atLocation($path, $e->getMessage(), $e);
|
||||
}
|
||||
|
||||
DB::table($this->table())->where('path', $path)->delete();
|
||||
}
|
||||
|
||||
public function deleteDirectory(string $path): void
|
||||
{
|
||||
throw UnableToDeleteDirectory::atLocation($path, 'The IriksIT storage has no folders.');
|
||||
}
|
||||
|
||||
public function createDirectory(string $path, Config $config): void
|
||||
{
|
||||
throw UnableToCreateDirectory::atLocation($path, 'The IriksIT storage has no folders.');
|
||||
}
|
||||
|
||||
public function setVisibility(string $path, string $visibility): void
|
||||
{
|
||||
throw UnableToSetVisibility::atLocation($path, 'The IriksIT storage has no visibility.');
|
||||
}
|
||||
|
||||
public function visibility(string $path): FileAttributes
|
||||
{
|
||||
throw UnableToRetrieveMetadata::visibility($path, 'The IriksIT storage has no visibility.');
|
||||
}
|
||||
|
||||
public function mimeType(string $path): FileAttributes
|
||||
{
|
||||
$details = $this->details($path, 'mime_type');
|
||||
|
||||
return new FileAttributes($path, null, null, null, $details['mime_type'] ?? throw UnableToRetrieveMetadata::mimeType($path));
|
||||
}
|
||||
|
||||
public function lastModified(string $path): FileAttributes
|
||||
{
|
||||
$created = $this->details($path, 'last_modified')['created_at'] ?? null;
|
||||
|
||||
return new FileAttributes($path, null, null, $created !== null ? strtotime($created) ?: null : throw UnableToRetrieveMetadata::lastModified($path));
|
||||
}
|
||||
|
||||
public function fileSize(string $path): FileAttributes
|
||||
{
|
||||
return new FileAttributes($path, $this->details($path, 'file_size')['size']);
|
||||
}
|
||||
|
||||
/** @return iterable<FileAttributes|DirectoryAttributes> */
|
||||
public function listContents(string $path, bool $deep): iterable
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function move(string $source, string $destination, Config $config): void
|
||||
{
|
||||
throw UnableToMoveFile::fromLocationTo($source, $destination);
|
||||
}
|
||||
|
||||
public function copy(string $source, string $destination, Config $config): void
|
||||
{
|
||||
throw UnableToCopyFile::fromLocationTo($source, $destination);
|
||||
}
|
||||
|
||||
/** @return array{size: int, mime_type: string|null, created_at: string|null} */
|
||||
private function details(string $path, string $what): array
|
||||
{
|
||||
$id = $this->id($path) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
|
||||
|
||||
try {
|
||||
return $this->client->details($id) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
|
||||
} catch (MediaStorageException $e) {
|
||||
throw UnableToRetrieveMetadata::create($path, $what, $e->getMessage(), $e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The id the API gave to what was written at this path, or the path itself when it looks like an id. */
|
||||
private function id(string $path): ?string
|
||||
{
|
||||
$id = DB::table($this->table())->where('path', $path)->value('remote_id');
|
||||
|
||||
if (is_string($id)) {
|
||||
return $id;
|
||||
}
|
||||
|
||||
return $path !== '' && ! str_contains($path, '/') ? $path : null;
|
||||
}
|
||||
|
||||
private function table(): string
|
||||
{
|
||||
return Names::table('storage_files');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\IriksStorage;
|
||||
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Talks to the IriksIT API (the `/storage` part of it): logs in with an account, keeps the token and the refresh token
|
||||
* (encrypted) in the cache, renews them, and stores, opens, describes and deletes files. The account needs the
|
||||
* `storage.read` and `storage.write` permissions. Every failure is a MediaStorageException; what the API says goes into
|
||||
* its message (never an address, a token or a password).
|
||||
*/
|
||||
class Client
|
||||
{
|
||||
private const TOKEN = 'manager.iriksit.token';
|
||||
|
||||
private const REFRESH = 'manager.iriksit.refresh';
|
||||
|
||||
/** @param array{url?: string|null, email?: string|null, password?: string|null, timeout?: int|string|null} $config */
|
||||
public function __construct(private readonly array $config) {}
|
||||
|
||||
/** Whether an address and an account are set at all. */
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->value('url') !== '' && $this->value('email') !== '' && $this->value('password') !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a file. The `id` that comes back is the only handle to it afterwards.
|
||||
*
|
||||
* @param resource $stream
|
||||
* @return array{id: string, size: int, mime_type: string|null, checksum: string|null}
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function store($stream, string $filename): array
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->attach('file', $stream, $filename)->post($this->url('/storage'), ['priority' => 'normal']));
|
||||
$data = $response->json('data');
|
||||
|
||||
if ($response->failed() || ! is_array($data) || ! is_string($data['id'] ?? null) || $data['id'] === '') {
|
||||
throw $this->failure('store a file', $response);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $data['id'],
|
||||
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
||||
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
||||
'checksum' => is_string($data['checksum'] ?? null) ? $data['checksum'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The content of a file as a stream; read it and close it.
|
||||
*
|
||||
* @throws MediaStorageException with status 404 when the API does not know the file
|
||||
*/
|
||||
public function open(string $id): StreamInterface
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download')));
|
||||
|
||||
if ($response->status() !== 200) {
|
||||
throw $this->failure('download a file', $response);
|
||||
}
|
||||
|
||||
return $response->toPsrResponse()->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* What the API knows of a file, or null when it does not know it.
|
||||
*
|
||||
* @return array{size: int, mime_type: string|null, created_at: string|null}|null
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function details(string $id): ?array
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->get($this->url('/storage/'.rawurlencode($id))));
|
||||
|
||||
if ($response->status() === 404) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = $response->json('data');
|
||||
|
||||
if ($response->failed() || ! is_array($data)) {
|
||||
throw $this->failure('read a file', $response);
|
||||
}
|
||||
|
||||
return [
|
||||
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
|
||||
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
|
||||
'created_at' => is_string($data['created_at'] ?? null) ? $data['created_at'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a file. One the API no longer knows counts as deleted.
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function delete(string $id): void
|
||||
{
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->delete($this->url('/storage/'.rawurlencode($id))));
|
||||
|
||||
if ($response->failed() && $response->status() !== 404) {
|
||||
throw $this->failure('delete a file', $response);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the account can log in at all: the check behind a "test the connection" button.
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
public function check(): void
|
||||
{
|
||||
$this->token();
|
||||
}
|
||||
|
||||
/**
|
||||
* What the tokens of pieces of work cost, as the API worked it out with the price list and the euro rate of each day
|
||||
* (`POST /tools/ai/cost`, permission `ai.pricing`). A row it has no price or rate for is left out; null when it cannot answer.
|
||||
*
|
||||
* @param list<array{reference: string, model: string, date: string, tokens: array<string, int>}> $items
|
||||
* @return array<string, array{usd: float, eur: float, usd_per_eur: float}>|null by reference
|
||||
*/
|
||||
public function tokenCosts(array $items): ?array
|
||||
{
|
||||
if (! $this->isConfigured() || $items === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->call(fn (PendingRequest $request) => $request->timeout(15)->post($this->url('/tools/ai/cost'), ['items' => $items]));
|
||||
} catch (MediaStorageException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$costs = [];
|
||||
$answer = $response->json('data.items');
|
||||
|
||||
foreach (is_array($answer) ? $answer : [] as $item) {
|
||||
if (! is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$reference = $item['reference'] ?? null;
|
||||
$usd = is_array($item['usd'] ?? null) ? ($item['usd']['total'] ?? null) : null;
|
||||
$rate = is_array($item['exchange_rate'] ?? null) ? ($item['exchange_rate']['usd_per_eur'] ?? null) : null;
|
||||
|
||||
if (is_string($reference) && is_numeric($usd) && is_numeric($item['eur'] ?? null) && is_numeric($rate) && (float) $rate > 0) {
|
||||
$costs[$reference] = ['usd' => (float) $usd, 'eur' => (float) $item['eur'], 'usd_per_eur' => (float) $rate];
|
||||
}
|
||||
}
|
||||
|
||||
return $costs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a call with the current token. A 401 means the token was revoked on the API's side: forget it, log in
|
||||
* again and try once more.
|
||||
*
|
||||
* @param \Closure(PendingRequest): Response $call
|
||||
*
|
||||
* @throws MediaStorageException
|
||||
*/
|
||||
private function call(\Closure $call): Response
|
||||
{
|
||||
try {
|
||||
$response = $call($this->request($this->token()));
|
||||
|
||||
if ($response->status() !== 401) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
Cache::forget(self::TOKEN);
|
||||
Cache::forget(self::REFRESH);
|
||||
|
||||
return $call($this->request($this->token()));
|
||||
} catch (MediaStorageException $e) {
|
||||
throw $e;
|
||||
} catch (Throwable) {
|
||||
throw new MediaStorageException('The IriksIT storage could not be reached.');
|
||||
}
|
||||
}
|
||||
|
||||
private function request(string $token): PendingRequest
|
||||
{
|
||||
$timeout = $this->config['timeout'] ?? null;
|
||||
|
||||
return Http::acceptJson()->withoutRedirecting()->withToken($token)->connectTimeout(5)->timeout(is_numeric($timeout) ? (int) $timeout : 300);
|
||||
}
|
||||
|
||||
/** @throws MediaStorageException */
|
||||
private function token(): string
|
||||
{
|
||||
$token = $this->cached(self::TOKEN);
|
||||
|
||||
if ($token !== null) {
|
||||
return $token;
|
||||
}
|
||||
|
||||
$refresh = $this->cached(self::REFRESH);
|
||||
|
||||
if ($refresh !== null) {
|
||||
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)->withToken($refresh)->post($this->url('/auth/refresh'));
|
||||
|
||||
if ($response->successful() && ($kept = $this->keep($response->json('data'))) !== null) {
|
||||
return $kept;
|
||||
}
|
||||
|
||||
Cache::forget(self::REFRESH);
|
||||
}
|
||||
|
||||
if (! $this->isConfigured()) {
|
||||
throw new MediaStorageException('No IriksIT account is set for the storage (address, email and password).');
|
||||
}
|
||||
|
||||
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)
|
||||
->post($this->url('/auth/login'), ['email' => $this->value('email'), 'password' => $this->value('password')]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new MediaStorageException("The IriksIT login failed (HTTP {$response->status()}).", $response->status());
|
||||
}
|
||||
|
||||
return $this->keep($response->json('data')) ?? throw new MediaStorageException('The IriksIT API sent a login answer without a token.');
|
||||
}
|
||||
|
||||
/** Remembers the tokens of a login answer until they expire (a minute early) and returns the access token. */
|
||||
private function keep(mixed $data): ?string
|
||||
{
|
||||
if (! is_array($data) || ! is_string($data['token'] ?? null) || $data['token'] === '' || ! is_string($data['expire'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Cache::put(self::TOKEN, Crypt::encryptString($data['token']), Carbon::parse($data['expire'])->subMinute());
|
||||
|
||||
if (is_string($data['refresh_token'] ?? null) && is_string($data['refresh_expire'] ?? null)) {
|
||||
Cache::put(self::REFRESH, Crypt::encryptString($data['refresh_token']), Carbon::parse($data['refresh_expire'])->subMinute());
|
||||
}
|
||||
|
||||
return $data['token'];
|
||||
}
|
||||
|
||||
private function cached(string $key): ?string
|
||||
{
|
||||
$value = Cache::get($key);
|
||||
|
||||
try {
|
||||
return is_string($value) ? Crypt::decryptString($value) : null;
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function failure(string $action, Response $response): MediaStorageException
|
||||
{
|
||||
$reason = $response->json('message');
|
||||
$detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : '';
|
||||
$retry = $response->header('Retry-After');
|
||||
|
||||
return new MediaStorageException(
|
||||
"The IriksIT storage could not {$action} (HTTP {$response->status()}{$detail}).",
|
||||
$response->status(),
|
||||
is_numeric($retry) ? (int) $retry : null,
|
||||
);
|
||||
}
|
||||
|
||||
private function url(string $path): string
|
||||
{
|
||||
return rtrim($this->value('url'), '/').$path;
|
||||
}
|
||||
|
||||
private function value(string $key): string
|
||||
{
|
||||
$value = $this->config[$key] ?? '';
|
||||
|
||||
return is_string($value) ? trim($value) : '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Leads;
|
||||
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use IriksIT\Manager\Mail\LeadConfirmation;
|
||||
use IriksIT\Manager\Mail\LeadReceived;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Modules\Statistics\VisitRecorder;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Takes a request in: screens it, stores it, and tells the owner and the visitor. The only code that creates a `Lead` from a form.
|
||||
* The forms themselves are the site's own (their fields, their words, their thank-you page); they validate, then call `take()`.
|
||||
*
|
||||
* A form never tells a sender that it was taken for spam: whatever the screening thinks, the visitor gets the normal thank-you.
|
||||
*/
|
||||
final class Intake
|
||||
{
|
||||
public function __construct(private readonly Screening $screening) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes what the form gave, already validated: kind, name, phone, email, message, about, answers, ...
|
||||
* @param int|null $seconds how long the form was open (see `secondsOpen()`)
|
||||
*/
|
||||
public function take(array $attributes, ?int $seconds, string $ip, string $userAgent = ''): Lead
|
||||
{
|
||||
$attributes['ip'] = $ip;
|
||||
$message = $attributes['message'] ?? null;
|
||||
|
||||
$lead = Lead::create([
|
||||
...$attributes,
|
||||
...$this->screening->screen($attributes, $seconds),
|
||||
'message_hash' => Lead::hashOf(is_string($message) ? $message : null),
|
||||
// Where the visit came from: a site that counts its visits says so (`manager.leads.source`, an invokable class
|
||||
// that gets the address and the browser and returns channel and source).
|
||||
...$this->source($ip, $userAgent),
|
||||
]);
|
||||
|
||||
// Only a real request is worth a mail: to the owner, and back to whoever sent it. A confirmation for junk would be mail
|
||||
// to an address someone else made up.
|
||||
if ($lead->folder === Lead::INBOX) {
|
||||
$this->tellTheOwner($lead);
|
||||
$this->confirm($lead);
|
||||
}
|
||||
|
||||
return $lead;
|
||||
}
|
||||
|
||||
/** Mails the owner. A mail that cannot be sent never loses the request: it is stored already. */
|
||||
public function tellTheOwner(Lead $lead): void
|
||||
{
|
||||
$to = (string) config('manager.leads.notify');
|
||||
|
||||
if ($to === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::to($to)->send(new LeadReceived($lead));
|
||||
$lead->update(['notified_at' => now(), 'notify_failed' => false]);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
$lead->update(['notify_failed' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
/** A signed moment for a form: sent back with it, it tells how long the form was open. */
|
||||
public static function formToken(): string
|
||||
{
|
||||
return Crypt::encryptString((string) now()->timestamp);
|
||||
}
|
||||
|
||||
/** How many seconds a form was open, or null when its token says nothing (missing, tampered with, too old). */
|
||||
public static function secondsOpen(string $token): ?int
|
||||
{
|
||||
if ($token === '' || strlen($token) > 1000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$seconds = now()->timestamp - (int) Crypt::decryptString($token);
|
||||
} catch (DecryptException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $seconds < 0 || $seconds > max(1, (int) config('manager.leads.max_hours', 24)) * 3600 ? null : $seconds;
|
||||
}
|
||||
|
||||
private function confirm(Lead $lead): void
|
||||
{
|
||||
if (! config('manager.leads.confirm') || $lead->email === null || $lead->email === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::to($lead->email)->send(new LeadConfirmation($lead));
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the visit came from. A site that counts its visits with the statistics module gets it for free; another source is
|
||||
* `manager.leads.source`, an invokable class that gets the address and the browser and returns `channel` and `source`.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function source(string $ip, string $userAgent): array
|
||||
{
|
||||
$class = config('manager.leads.source');
|
||||
|
||||
try {
|
||||
if (is_string($class) && class_exists($class)) {
|
||||
$found = (array) app($class)($ip, $userAgent);
|
||||
} elseif (app(ModuleRegistry::class)->enabled('statistics')) {
|
||||
$found = app(VisitRecorder::class)->sourceOf($ip, $userAgent);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_intersect_key($found, ['channel' => 1, 'source' => 1]);
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Leads;
|
||||
|
||||
/**
|
||||
* A phone number as people write it ("06 12 34 56 78", "+31 6 12345678") turned into digits with the country code. A number that
|
||||
* starts with a single 0 is taken to be of the home country (`manager.leads.country_code`, 31 unless the site says otherwise).
|
||||
*/
|
||||
final class Phone
|
||||
{
|
||||
/** "31612345678", or null for anything that is no phone number. */
|
||||
public static function international(string $number): ?string
|
||||
{
|
||||
$number = trim($number);
|
||||
|
||||
if ($number === '' || preg_match('/^[\d\s().+\-\/]+$/', $number) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// "+31 (0)6 12345678": the zero between brackets is not dialled after a country code.
|
||||
$number = str_starts_with($number, '+') || str_starts_with($number, '00') ? str_replace('(0)', '', $number) : $number;
|
||||
$digits = preg_replace('/\D+/', '', $number) ?? '';
|
||||
|
||||
if (str_starts_with($number, '+')) {
|
||||
// already has its country code
|
||||
} elseif (str_starts_with($digits, '00')) {
|
||||
$digits = substr($digits, 2);
|
||||
} elseif (str_starts_with($digits, '0')) {
|
||||
$digits = self::country().substr($digits, 1);
|
||||
}
|
||||
|
||||
return strlen($digits) >= 9 && strlen($digits) <= 15 ? $digits : null;
|
||||
}
|
||||
|
||||
/** Whether the number is of the home country. */
|
||||
public static function isHome(string $number): bool
|
||||
{
|
||||
$digits = self::international($number);
|
||||
|
||||
return $digits !== null && str_starts_with($digits, self::country());
|
||||
}
|
||||
|
||||
private static function country(): string
|
||||
{
|
||||
return preg_replace('/\D+/', '', (string) config('manager.leads.country_code', '31')) ?: '31';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Leads;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadTap;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/**
|
||||
* What the forms and the contact buttons brought in over a number of days: how many requests, through which way in, from which page and
|
||||
* which source, how many became a job, and how much the screening kept away. For whoever manages the requests. Counted in PHP from a
|
||||
* handful of columns, so it reads the same on SQLite and MySQL.
|
||||
*/
|
||||
final class Report
|
||||
{
|
||||
/** One tap on a contact button, counted for a page: a counter and nothing else. */
|
||||
public static function tap(string $kind, string $path): void
|
||||
{
|
||||
if (! in_array($kind, [LeadTap::CALL, LeadTap::WHATSAPP], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$table = Names::table('lead_taps');
|
||||
|
||||
// One statement, so two taps at the same moment both count.
|
||||
DB::table($table)->upsert([['day' => now()->toDateString(), 'kind' => $kind, 'path' => mb_substr($path, 0, 255), 'taps' => 1]], ['day', 'kind', 'path'], ['taps' => DB::raw($table.'.taps + 1')]);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function over(int $days): array
|
||||
{
|
||||
$since = now()->subDays($days - 1)->startOfDay();
|
||||
|
||||
/** @var Collection<int, Lead> $leads */
|
||||
$leads = Lead::query()->where('created_at', '>=', $since)->get(['id', 'kind', 'folder', 'page', 'channel', 'source', 'subject', 'outcome', 'handled_at']);
|
||||
$real = $leads->where('folder', Lead::INBOX);
|
||||
$taps = LeadTap::query()->where('day', '>=', $since->toDateString())->get(['kind', 'path', 'taps']);
|
||||
|
||||
$ways = [
|
||||
['name' => __('Calls (taps on the number)'), 'count' => self::total($taps->where('kind', LeadTap::CALL))],
|
||||
['name' => __('WhatsApp (taps on the button)'), 'count' => self::total($taps->where('kind', LeadTap::WHATSAPP))],
|
||||
];
|
||||
|
||||
foreach ((array) config('manager.leads.kinds', []) as $kind => $label) {
|
||||
$ways[] = ['name' => __((string) $label), 'count' => $real->where('kind', $kind)->count()];
|
||||
}
|
||||
|
||||
return [
|
||||
'days' => $days,
|
||||
'requests' => $real->count(),
|
||||
'kept_away' => ['other' => $leads->where('folder', Lead::OTHER)->count(), 'spam' => $leads->where('folder', Lead::SPAM)->count()],
|
||||
'won' => $real->where('outcome', Lead::WON)->count(),
|
||||
'lost' => $real->where('outcome', Lead::LOST)->count(),
|
||||
'waiting' => $real->whereNull('handled_at')->count(),
|
||||
'ways' => $ways,
|
||||
'pages' => self::top($real->groupBy(fn (Lead $lead) => $lead->page ?? '(unknown)')),
|
||||
'sources' => self::top($real->groupBy(fn (Lead $lead) => trim(($lead->channel ?? 'unknown').($lead->source ? ': '.$lead->source : '')))),
|
||||
'subjects' => self::top($real->groupBy(fn (Lead $lead) => $lead->subject ?: '(none)')),
|
||||
'tap_pages' => $taps->groupBy('path')->map(fn (Collection $rows, string $path) => ['name' => $path, 'count' => self::total($rows)])->sortByDesc('count')->take(8)->values()->all(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param Collection<int, LeadTap> $taps */
|
||||
private static function total(Collection $taps): int
|
||||
{
|
||||
return $taps->reduce(fn (int $sum, LeadTap $tap) => $sum + $tap->taps, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The largest groups, with how many of each became a job.
|
||||
*
|
||||
* @param Collection<array-key, Collection<int, Lead>> $groups
|
||||
* @return list<array{name: string, count: int, won: int}>
|
||||
*/
|
||||
private static function top(Collection $groups): array
|
||||
{
|
||||
return array_values($groups->map(fn (Collection $leads, int|string $name) => [
|
||||
'name' => (string) $name, 'count' => $leads->count(), 'won' => $leads->where('outcome', Lead::WON)->count(),
|
||||
])->sortByDesc('count')->take(8)->values()->all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Leads;
|
||||
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadBlock;
|
||||
|
||||
/**
|
||||
* Decides in which folder a request lands: the inbox (a real request), "other" (acquisition and what the visitor called something
|
||||
* else) or spam. The only code that decides a folder. Nothing is refused here: a sender always gets the normal thank-you, and the
|
||||
* worst that happens to a real customer with an odd message is the folder "other". The reasons are kept with the request, so a wrong
|
||||
* call can be seen and undone. All rules and thresholds are in `manager.leads`.
|
||||
*/
|
||||
final class Screening
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $lead the attributes of the request
|
||||
* @param int|null $seconds how long the form was open; null when that could not be told
|
||||
* @return array{folder: string, reasons: list<string>}
|
||||
*/
|
||||
public function screen(array $lead, ?int $seconds): array
|
||||
{
|
||||
$message = self::text($lead['message'] ?? null);
|
||||
$email = mb_strtolower(self::text($lead['email'] ?? null));
|
||||
$phone = self::text($lead['phone'] ?? null);
|
||||
$ip = self::text($lead['ip'] ?? null);
|
||||
|
||||
if (($block = $this->blocked($email, $phone, $ip)) !== null) {
|
||||
return ['folder' => Lead::SPAM, 'reasons' => [$block]];
|
||||
}
|
||||
|
||||
$spam = 0;
|
||||
$other = 0;
|
||||
$reasons = [];
|
||||
|
||||
$links = preg_match_all('#https?://|www\.|\b[a-z0-9-]+\.(?:com|net|org|info|biz|ru|cn|xyz|top|online|site)\b#i', $message);
|
||||
if ($links > 0) {
|
||||
$spam += $links > 1 ? 5 : 3;
|
||||
$reasons[] = $links > 1 ? 'Several links in the text' : 'A link in the text';
|
||||
}
|
||||
|
||||
$words = $this->acquisitionWords($message);
|
||||
if ($words !== []) {
|
||||
$other += min(6, 2 * count($words));
|
||||
$reasons[] = 'Words of selling to a business: '.implode(', ', array_slice($words, 0, 5));
|
||||
}
|
||||
|
||||
if ($message !== '' && ! $this->inExpectedLanguage($message)) {
|
||||
$spam += 3;
|
||||
$reasons[] = 'The text is not in the expected language';
|
||||
}
|
||||
|
||||
if ($seconds === null) {
|
||||
$spam += 2;
|
||||
$reasons[] = 'The form could not tell how long it was open';
|
||||
} elseif ($seconds < self::number('min_seconds')) {
|
||||
$spam += 4;
|
||||
$reasons[] = "Sent within {$seconds} seconds of opening the form";
|
||||
}
|
||||
|
||||
if ($email !== '' && in_array(substr((string) strrchr($email, '@'), 1), self::list('throwaway_domains'), true)) {
|
||||
$spam += 4;
|
||||
$reasons[] = 'A throwaway mail address';
|
||||
}
|
||||
|
||||
$hash = Lead::hashOf($message);
|
||||
if ($hash !== null && Lead::query()->where('message_hash', $hash)->exists()) {
|
||||
$spam += 4;
|
||||
$reasons[] = 'The same text was sent before';
|
||||
}
|
||||
|
||||
// Worth knowing, but no reason to put a request aside: it may be a holiday home.
|
||||
if ($phone !== '' && ! Phone::isHome($phone)) {
|
||||
$reasons[] = 'Note: the phone number is not of this country';
|
||||
}
|
||||
|
||||
$chosenOther = ($lead['about'] ?? 'job') === 'other';
|
||||
$folder = match (true) {
|
||||
$spam >= self::number('spam_from') => Lead::SPAM,
|
||||
$chosenOther, $other >= self::number('other_from') => Lead::OTHER,
|
||||
default => Lead::INBOX,
|
||||
};
|
||||
|
||||
if ($chosenOther) {
|
||||
array_unshift($reasons, 'The visitor chose "something else"');
|
||||
}
|
||||
|
||||
return ['folder' => $folder, 'reasons' => $reasons];
|
||||
}
|
||||
|
||||
/** Why this sender is kept out, or null when they are not. */
|
||||
private function blocked(string $email, string $phone, string $ip): ?string
|
||||
{
|
||||
$domain = $email !== '' ? substr((string) strrchr($email, '@'), 1) : '';
|
||||
$digits = $phone !== '' ? Phone::international($phone) : null;
|
||||
|
||||
$block = LeadBlock::query()
|
||||
->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
->where(function ($query) use ($email, $domain, $digits, $ip) {
|
||||
$query->whereRaw('1 = 0');
|
||||
foreach ([[LeadBlock::EMAIL, $email], [LeadBlock::DOMAIN, $domain], [LeadBlock::PHONE, (string) $digits], [LeadBlock::IP, $ip]] as [$type, $value]) {
|
||||
if ($value !== '') {
|
||||
$query->orWhere(fn ($q) => $q->where('type', $type)->where('value', $value));
|
||||
}
|
||||
}
|
||||
})->first();
|
||||
|
||||
return $block instanceof LeadBlock ? 'This sender is blocked ('.$block->type.')' : null;
|
||||
}
|
||||
|
||||
/** @return list<string> the words of the list that are in the text, as whole words */
|
||||
private function acquisitionWords(string $message): array
|
||||
{
|
||||
$text = ' '.preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower($message)).' ';
|
||||
|
||||
return array_values(array_filter(self::list('acquisition_words'), fn (string $word) => str_contains($text, ' '.$word.' ')));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a text is in the language the site expects (`manager.leads.language`: `nl`, `en` or null for no check): it has no
|
||||
* other alphabet, and of the small words every sentence has the expected language is not outnumbered by the other one.
|
||||
* A text too short to tell counts as fine.
|
||||
*/
|
||||
private function inExpectedLanguage(string $message): bool
|
||||
{
|
||||
$language = config('manager.leads.language');
|
||||
|
||||
if (! in_array($language, ['nl', 'en'], true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (preg_match('/[\p{Cyrillic}\p{Han}\p{Arabic}\p{Hebrew}\p{Thai}\p{Hangul}\p{Hiragana}\p{Katakana}]/u', $message) === 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$words = preg_split('/[^\p{L}]+/u', mb_strtolower($message), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
|
||||
if (count($words) < 6) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$dutch = count(array_intersect($words, ['de', 'het', 'een', 'en', 'ik', 'wij', 'we', 'van', 'voor', 'met', 'niet', 'is', 'zijn', 'op', 'dat', 'die', 'graag', 'ook', 'bij', 'naar', 'om', 'te', 'er', 'aan', 'mijn', 'onze', 'u', 'je', 'kan', 'kunt', 'wil', 'hebben', 'heb', 'of', 'als', 'maar']));
|
||||
$english = count(array_intersect($words, ['the', 'and', 'you', 'your', 'our', 'for', 'with', 'that', 'this', 'are', 'have', 'will', 'can', 'to', 'of', 'in', 'on', 'it', 'be', 'from', 'would', 'please', 'hello', 'hi', 'dear']));
|
||||
|
||||
return $language === 'nl' ? ($english === 0 || $dutch >= $english) : ($dutch === 0 || $english >= $dutch);
|
||||
}
|
||||
|
||||
private static function text(mixed $value): string
|
||||
{
|
||||
return is_string($value) ? trim($value) : '';
|
||||
}
|
||||
|
||||
private static function number(string $key): int
|
||||
{
|
||||
$value = config("manager.leads.{$key}");
|
||||
|
||||
return is_numeric($value) ? (int) $value : 0;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private static function list(string $key): array
|
||||
{
|
||||
$value = config("manager.leads.{$key}");
|
||||
|
||||
return is_array($value) ? array_values(array_filter($value, 'is_string')) : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Login;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Contracts\LoginCheck;
|
||||
|
||||
/** Extend this and override what the check needs. */
|
||||
abstract class BaseLoginCheck implements LoginCheck
|
||||
{
|
||||
public function fields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function before(Request $request): void {}
|
||||
|
||||
public function after(Request $request, Authenticatable $user): void {}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Login;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Cloudflare Turnstile on the login. On by itself when `MANAGER_TURNSTILE_SITE_KEY` and `MANAGER_TURNSTILE_SECRET` are set. A token that
|
||||
* cannot be checked (Cloudflare does not answer) refuses the login: a captcha that lets everyone in when it is down protects nothing.
|
||||
*/
|
||||
final class Turnstile extends BaseLoginCheck
|
||||
{
|
||||
private const VERIFY = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
||||
|
||||
public static function configured(): bool
|
||||
{
|
||||
return (string) config('manager.login.turnstile.site_key') !== '' && (string) config('manager.login.turnstile.secret') !== '';
|
||||
}
|
||||
|
||||
public function fields(): array
|
||||
{
|
||||
return [['name' => 'turnstile', 'type' => 'turnstile', 'site_key' => (string) config('manager.login.turnstile.site_key')]];
|
||||
}
|
||||
|
||||
public function before(Request $request): void
|
||||
{
|
||||
$token = $request->string('turnstile')->limit(2048, '')->toString();
|
||||
|
||||
if ($token === '' || ! self::passes($token, (string) $request->ip())) {
|
||||
throw ValidationException::withMessages(['turnstile' => __('Prove you are not a program, then log in again.')]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether Cloudflare says this token is good. A token that cannot be checked is not good. Also used by the public forms. */
|
||||
public static function passes(string $token, string $ip): bool
|
||||
{
|
||||
try {
|
||||
$answer = Http::asForm()->timeout(5)->post(self::VERIFY, ['secret' => config('manager.login.turnstile.secret'), 'response' => $token, 'remoteip' => $ip]);
|
||||
|
||||
return $answer->ok() && $answer->json('success') === true;
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Contracts\LoginCheck;
|
||||
use IriksIT\Manager\Support\Login\Turnstile;
|
||||
|
||||
/** The checks a login runs, from config `manager.login.checks` (and Turnstile when it is set up). */
|
||||
final class LoginChecks
|
||||
{
|
||||
/** @return list<LoginCheck> */
|
||||
public function all(): array
|
||||
{
|
||||
$classes = array_values(array_unique([...(array) config('manager.login.checks', []), ...(Turnstile::configured() ? [Turnstile::class] : [])]));
|
||||
$checks = [];
|
||||
|
||||
foreach ($classes as $class) {
|
||||
if (is_string($class) && is_subclass_of($class, LoginCheck::class)) {
|
||||
$checks[] = app($class);
|
||||
}
|
||||
}
|
||||
|
||||
return $checks;
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
public function fields(): array
|
||||
{
|
||||
return array_merge(...array_map(fn (LoginCheck $check) => $check->fields(), $this->all()) ?: [[]]);
|
||||
}
|
||||
|
||||
public function before(Request $request): void
|
||||
{
|
||||
foreach ($this->all() as $check) {
|
||||
$check->before($request);
|
||||
}
|
||||
}
|
||||
|
||||
public function after(Request $request, Authenticatable $user): void
|
||||
{
|
||||
foreach ($this->all() as $check) {
|
||||
$check->after($request, $user);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use League\CommonMark\Extension\ExternalLink\ExternalLinkExtension;
|
||||
|
||||
/**
|
||||
* Posts are written in Markdown. Raw HTML in a post is escaped, so the rendered output is safe
|
||||
* to print. Links to other hosts open in a new window; `manager.markdown.internal_hosts` lists
|
||||
* more hosts that count as this site.
|
||||
*/
|
||||
final class Markdown
|
||||
{
|
||||
public static function toHtml(string $markdown): string
|
||||
{
|
||||
$host = parse_url((string) config('app.url'), PHP_URL_HOST);
|
||||
|
||||
return Str::markdown($markdown, [
|
||||
'html_input' => 'escape',
|
||||
'allow_unsafe_links' => false,
|
||||
'external_link' => [
|
||||
'internal_hosts' => array_values(array_filter([$host, ...(array) config('manager.markdown.internal_hosts', [])])),
|
||||
'open_in_new_window' => true,
|
||||
'noopener' => 'external',
|
||||
'noreferrer' => 'external',
|
||||
],
|
||||
], [new ExternalLinkExtension]);
|
||||
}
|
||||
|
||||
public static function toPlainText(string $markdown): string
|
||||
{
|
||||
$text = strip_tags(self::toHtml($markdown));
|
||||
|
||||
return trim((string) preg_replace('/\s+/', ' ', html_entity_decode($text, ENT_QUOTES | ENT_HTML5)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Where media is used. A module or the host app registers a source: a closure that returns the
|
||||
* texts which may contain the address of a media file (a post body, a cover, a page text).
|
||||
* The media library counts the files whose address appears in them. No sources, no counts.
|
||||
*/
|
||||
final class MediaUsage
|
||||
{
|
||||
/** @var list<Closure(): iterable<mixed>> */
|
||||
private array $sources = [];
|
||||
|
||||
/** @param Closure(): iterable<mixed> $source */
|
||||
public function register(Closure $source): void
|
||||
{
|
||||
$this->sources[] = $source;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function haystacks(): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach ($this->sources as $source) {
|
||||
foreach ($source() as $text) {
|
||||
$texts[] = is_string($text) ? $text : '';
|
||||
}
|
||||
}
|
||||
|
||||
return $texts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
|
||||
/**
|
||||
* The menu one account sees, and the face of the manager it looks at: the full one, or (when config
|
||||
* `simple_view` is on) the simple one with only the items marked `simple`. An account with the permission
|
||||
* `manager.full` (and a super admin) gets the full face; everyone else the simple face, unless something is stored for
|
||||
* the account: an administrator sets it on the accounts screen, an account with `manager.switch` (or `manager.full`)
|
||||
* sets it itself. What is stored wins; only the account's own switch needs the permission.
|
||||
*/
|
||||
final class Menu
|
||||
{
|
||||
public const FULL = 'full';
|
||||
|
||||
public const SIMPLE = 'simple';
|
||||
|
||||
public function __construct(private readonly ModuleRegistry $modules) {}
|
||||
|
||||
public function view(?object $user): string
|
||||
{
|
||||
if ($user === null || ! config('manager.simple_view')) {
|
||||
return self::FULL;
|
||||
}
|
||||
|
||||
// What is stored wins: an administrator sets it for an account, an account that may switch sets it itself.
|
||||
$stored = UserSetting::value($user, 'view');
|
||||
|
||||
if (in_array($stored, [self::FULL, self::SIMPLE], true)) {
|
||||
return $stored;
|
||||
}
|
||||
|
||||
return $this->hasFull($user) ? self::FULL : self::SIMPLE;
|
||||
}
|
||||
|
||||
public function maySwitch(?object $user): bool
|
||||
{
|
||||
return $user !== null && config('manager.simple_view') && ($this->hasFull($user) || Gate::forUser($user)->allows('manager.switch'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $allowed the permissions this account has
|
||||
* @return list<array{label: string, href: string, section?: string, icon?: string, new_tab?: bool}>
|
||||
*/
|
||||
public function for(?object $user, array $allowed): array
|
||||
{
|
||||
if ($user === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$simple = $this->view($user) === self::SIMPLE;
|
||||
$items = [];
|
||||
|
||||
foreach ($this->modules->navigation() as $item) {
|
||||
if (($item['permission'] ?? null) !== null && ! in_array($item['permission'], $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($simple && ! $item['simple']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = array_filter([
|
||||
'label' => $simple ? ($item['simple_label'] ?? $item['label']) : $item['label'],
|
||||
'href' => isset($item['route']) ? route($item['route'], $item['params'] ?? [], false) : (string) $item['url'],
|
||||
'section' => $item['section'] ?? null,
|
||||
'hint' => $item['hint'] ?? null,
|
||||
'icon' => $item['icon'] ?? null,
|
||||
'new_tab' => ($item['new_tab'] ?? false) ?: null,
|
||||
], fn ($value) => $value !== null);
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function hasFull(object $user): bool
|
||||
{
|
||||
return (method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()) || Gate::forUser($user)->allows('manager.full');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Contracts\Module;
|
||||
use IriksIT\Manager\Exceptions\ModuleException;
|
||||
use IriksIT\Manager\Http\Controllers\MascotController;
|
||||
|
||||
/**
|
||||
* Knows which modules exist and which of them are on for this site.
|
||||
*/
|
||||
final class ModuleRegistry
|
||||
{
|
||||
/** @var array<string, Module> */
|
||||
private array $all = [];
|
||||
|
||||
/**
|
||||
* @param list<class-string<Module>> $available
|
||||
* @param array<string, bool> $switches
|
||||
*/
|
||||
public function __construct(array $available, private readonly array $switches)
|
||||
{
|
||||
foreach ($available as $class) {
|
||||
$module = new $class;
|
||||
$this->all[$module->key()] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, Module> every known module */
|
||||
public function all(): array
|
||||
{
|
||||
return $this->all;
|
||||
}
|
||||
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return isset($this->all[$key]);
|
||||
}
|
||||
|
||||
public function enabled(string $key): bool
|
||||
{
|
||||
if (! $this->has($key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A feature of the site with the name of the module is its one switch (see `Features`).
|
||||
$feature = Features::all()[$key] ?? null;
|
||||
|
||||
if ($feature !== null) {
|
||||
return $feature['enabled'];
|
||||
}
|
||||
|
||||
return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault());
|
||||
}
|
||||
|
||||
/** @return array<string, Module> the modules that are on */
|
||||
public function active(): array
|
||||
{
|
||||
return array_filter($this->all, fn (Module $module) => $this->enabled($module->key()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A module that is on while one it needs is off is a configuration mistake: fail loudly at boot.
|
||||
*/
|
||||
public function validate(): void
|
||||
{
|
||||
foreach ($this->active() as $module) {
|
||||
foreach ($module->requires() as $needed) {
|
||||
if (! $this->enabled($needed)) {
|
||||
throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, Permission> permission value => permission, of the active modules only */
|
||||
public function permissions(): array
|
||||
{
|
||||
$permissions = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
foreach ($module->permissions() as $permission) {
|
||||
$permissions[$permission->value] = $permission;
|
||||
}
|
||||
}
|
||||
|
||||
if (config('manager.simple_view')) {
|
||||
$permissions['manager.full'] = new Permission('manager.full', 'See the whole manager, not only the simple screens', 'Manager');
|
||||
$permissions['manager.switch'] = new Permission('manager.switch', 'Switch between the simple and the whole manager', 'Manager');
|
||||
}
|
||||
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function permissionValues(): array
|
||||
{
|
||||
return array_keys($this->permissions());
|
||||
}
|
||||
|
||||
/**
|
||||
* The given values without what is no permission (any more), completed with what they
|
||||
* need, in the order of the permissions.
|
||||
*
|
||||
* @param array<array-key, mixed> $values
|
||||
* @return list<string>
|
||||
*/
|
||||
public function complete(array $values): array
|
||||
{
|
||||
$known = $this->permissions();
|
||||
$wanted = [];
|
||||
|
||||
foreach ($values as $value) {
|
||||
if (is_string($value) && isset($known[$value])) {
|
||||
$wanted[$value] = true;
|
||||
|
||||
foreach ($known[$value]->needs as $needed) {
|
||||
$wanted[$needed] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_filter(array_keys($known), fn (string $value) => isset($wanted[$value])));
|
||||
}
|
||||
|
||||
/**
|
||||
* The list for the group form, per section.
|
||||
*
|
||||
* @return list<array{section: string, permissions: list<array{value: string, label: string, needs: list<string>}>}>
|
||||
*/
|
||||
public function catalogue(): array
|
||||
{
|
||||
$sections = [];
|
||||
|
||||
foreach ($this->permissions() as $permission) {
|
||||
$sections[__($permission->section)][] = ['value' => $permission->value, 'label' => __($permission->label), 'needs' => $permission->needs];
|
||||
}
|
||||
|
||||
$catalogue = [];
|
||||
foreach ($sections as $section => $permissions) {
|
||||
$catalogue[] = ['section' => $section, 'permissions' => $permissions];
|
||||
}
|
||||
|
||||
return $catalogue;
|
||||
}
|
||||
|
||||
/**
|
||||
* The menu: what the modules give, changed by config `manager.menu`, in order. An item has `label`,
|
||||
* `route` (or `url` for a link of the site's own) and `permission`, and may add `section` (a heading),
|
||||
* `icon`, `order` (lower comes first; default 100), `simple` (shown in the simple view) and `new_tab`.
|
||||
*
|
||||
* @return list<array{label: string, route?: string, url?: string, permission: ?string, section?: string, icon?: string, order: int, simple: bool, new_tab?: bool}>
|
||||
*/
|
||||
public function navigation(): array
|
||||
{
|
||||
$changes = (array) config('manager.menu.items', []);
|
||||
$items = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
foreach ($module->navigation() as $item) {
|
||||
$short = $item['id'] ?? (isset($item['route']) ? Str::after($item['route'], Names::routePrefix()) : '');
|
||||
$item = [...$item, ...(array) ($changes[$short] ?? [])];
|
||||
|
||||
if (($item['hidden'] ?? false) === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) config('manager.menu.links', []) as $link) {
|
||||
if (is_array($link) && isset($link['label'], $link['url'])) {
|
||||
$items[] = $link + ['permission' => null];
|
||||
}
|
||||
}
|
||||
|
||||
$items = array_map(fn (array $item) => [
|
||||
...$item,
|
||||
'label' => __($item['label']),
|
||||
...(isset($item['simple_label']) && $item['simple_label'] !== null ? ['simple_label' => __($item['simple_label'])] : []),
|
||||
...(isset($item['section']) ? ['section' => __($item['section'])] : []),
|
||||
...(isset($item['hint']) && $item['hint'] !== null ? ['hint' => __($item['hint'])] : []),
|
||||
'order' => (int) ($item['order'] ?? 100),
|
||||
'simple' => (bool) ($item['simple'] ?? false),
|
||||
], $items);
|
||||
|
||||
// PHP's sort is stable: items with the same order keep the order of the modules.
|
||||
usort($items, fn (array $a, array $b) => $a['order'] <=> $b['order']);
|
||||
|
||||
return array_values($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* The steps the modules add to the tour, for an account with these permissions.
|
||||
*
|
||||
* @param list<string> $allowed
|
||||
* @return list<array{title: string, text: string, image: ?string, href: ?string}>
|
||||
*/
|
||||
public function tutorial(array $allowed): array
|
||||
{
|
||||
$steps = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
foreach (method_exists($module, 'tutorial') ? $module->tutorial() : [] as $step) {
|
||||
if (! isset($step['title'], $step['text']) || (isset($step['permission']) && ! in_array($step['permission'], $allowed, true))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'title' => __($step['title']),
|
||||
'text' => __($step['text']),
|
||||
'image' => isset($step['image']) && in_array($step['image'], MascotController::NAMES, true) ? $step['image'] : null,
|
||||
'href' => isset($step['menu']) ? route(Names::route($step['menu']), [], false) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit-log names of what is done: the modules' own plus the core's.
|
||||
*
|
||||
* @return array<string, array{0: string, 1?: list<string>}>
|
||||
*/
|
||||
public function actions(): array
|
||||
{
|
||||
$actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager'], 'profile.tutorial' => ['Finished or skipped the tour']];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
$actions = [...$actions, ...$module->actions()];
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function views(): array
|
||||
{
|
||||
$views = ['dashboard' => 'Opened the dashboard', 'profile.show' => 'Opened own account'];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
$views = [...$views, ...$module->views()];
|
||||
}
|
||||
|
||||
return $views;
|
||||
}
|
||||
|
||||
/** @return list<string> middleware of the active modules for `before` or `after` the site's own */
|
||||
public function middleware(string $position): array
|
||||
{
|
||||
$middleware = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
array_push($middleware, ...($module->middleware()[$position] ?? []));
|
||||
}
|
||||
|
||||
return $middleware;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* The names the package gives to its routes and tables, so a site that already uses `manager.*`
|
||||
* route names or `manager_*` tables can move them out of the way (config `route_name`,
|
||||
* `table_prefix`, `tables`). The defaults are the names of every earlier version.
|
||||
*/
|
||||
final class Names
|
||||
{
|
||||
/** The full name of a package route, e.g. `posts.index` becomes `manager.posts.index`. */
|
||||
public static function route(string $name): string
|
||||
{
|
||||
return self::routePrefix().$name;
|
||||
}
|
||||
|
||||
/** The prefix of every route name, with its closing dot: `manager.` unless the site changed it. */
|
||||
public static function routePrefix(): string
|
||||
{
|
||||
$prefix = trim((string) config('manager.route_name', 'manager'), '.');
|
||||
|
||||
return $prefix === '' ? '' : $prefix.'.';
|
||||
}
|
||||
|
||||
/** The table for a package table such as `posts`: a name set in `tables`, else prefix + name. */
|
||||
public static function table(string $name): string
|
||||
{
|
||||
$custom = config('manager.tables.'.$name);
|
||||
|
||||
return is_string($custom) && $custom !== '' ? $custom : config('manager.table_prefix').$name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Collection;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\LeadTap;
|
||||
use IriksIT\Manager\Modules\Statistics\Statistics;
|
||||
|
||||
/**
|
||||
* How the site is doing, for the owner of the business: a few numbers in plain words, about people only (no rates, no technical terms,
|
||||
* nothing to choose but the period). The full statistics are for whoever looks after the site. Built on the statistics module; what
|
||||
* the contact buttons and the forms brought in comes from the requests module, when that is on and the account may read it.
|
||||
*/
|
||||
final class Numbers
|
||||
{
|
||||
/** The periods that can be chosen: the range of the statistics, and the words for it. */
|
||||
public const PERIODS = ['7d' => '7 days', '30d' => '30 days', '12m' => 'A year'];
|
||||
|
||||
public const DEFAULT_PERIOD = '30d';
|
||||
|
||||
private const LABELS = ['7d' => 'The last 7 days', '30d' => 'The last 30 days', '12m' => 'The last 12 months'];
|
||||
|
||||
private const BEFORE = ['7d' => 'the 7 days before', '30d' => 'the 30 days before', '12m' => 'the 12 months before'];
|
||||
|
||||
/** How a visit began, in the words of someone who does not build sites. */
|
||||
private const WAYS = [
|
||||
'search' => 'Through Google or another search engine',
|
||||
'direct' => 'Straight to the site: the address typed or saved',
|
||||
'social' => 'Through social media',
|
||||
'share' => 'Through a post the site shared itself',
|
||||
'referral' => 'Through a link on another site',
|
||||
'campaign' => 'Through a campaign or an advertisement',
|
||||
];
|
||||
|
||||
public function __construct(private readonly Statistics $statistics, private readonly ModuleRegistry $modules) {}
|
||||
|
||||
/** The key of a period that can be chosen; anything else is the default. */
|
||||
public static function period(string $key): string
|
||||
{
|
||||
return isset(self::PERIODS[$key]) ? $key : self::DEFAULT_PERIOD;
|
||||
}
|
||||
|
||||
/** Visitors of the last seven days, for the line under the button on the start screen. */
|
||||
public function visitorsThisWeek(): int
|
||||
{
|
||||
return $this->statistics->brief('7d')['totals']['visitors'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $withRequests whether the account may read the requests
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function over(string $key, bool $withRequests): array
|
||||
{
|
||||
$key = self::period($key);
|
||||
$brief = $this->statistics->brief($key);
|
||||
|
||||
$periods = [];
|
||||
|
||||
foreach (self::PERIODS as $name => $button) {
|
||||
$periods[] = ['key' => $name, 'button' => __($button)];
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach ($brief['channels'] as $channel) {
|
||||
$found[] = ['name' => __(self::WAYS[$channel['name']] ?? 'In another way'), 'visits' => $channel['visits']];
|
||||
}
|
||||
|
||||
$leads = $this->modules->enabled('leads');
|
||||
|
||||
return [
|
||||
'period' => ['key' => $key, 'label' => __(self::LABELS[$key]), 'before' => __(self::BEFORE[$key])],
|
||||
'periods' => $periods,
|
||||
'visitors' => $brief['totals']['visitors'],
|
||||
'visitors_before' => $brief['previous']['visitors'] ?? null,
|
||||
'page_views' => $brief['totals']['page_views'],
|
||||
'steps' => array_map(fn (array $step) => ['label' => $step['label'], 'visitors' => $step['visitors']], $brief['series']),
|
||||
'pages' => array_map(fn (array $page) => ['name' => $page['title'] ?? $page['path'], 'path' => $page['path'], 'views' => $page['views']], $brief['pages']),
|
||||
'found' => $found,
|
||||
'articles' => array_map(fn (array $post) => ['title' => $post['title'], 'views' => $post['views']], array_slice($brief['posts'], 0, 5)),
|
||||
'contact' => $leads ? ['calls' => $this->taps(LeadTap::CALL, $brief['from'], $brief['to']), 'whatsapp' => $this->taps(LeadTap::WHATSAPP, $brief['from'], $brief['to'])] : null,
|
||||
// What came in is only for who may read the requests.
|
||||
'requests' => $leads && $withRequests ? $this->requests($brief['from'], $brief['to']) : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function taps(string $kind, string $from, string $to): int
|
||||
{
|
||||
return (int) LeadTap::query()->whereBetween('day', [$from, $to])->where('kind', $kind)->sum('taps');
|
||||
}
|
||||
|
||||
/**
|
||||
* The requests of the period: how many were real, what became of them, and what they were about.
|
||||
*
|
||||
* @return array{count: int, won: int, waiting: int, kept_away: int, subjects: list<array{name: string, count: int}>}
|
||||
*/
|
||||
private function requests(string $from, string $to): array
|
||||
{
|
||||
/** @var Collection<int, Lead> $leads */
|
||||
$leads = Lead::query()
|
||||
->whereBetween('created_at', [CarbonImmutable::parse($from)->startOfDay(), CarbonImmutable::parse($to)->endOfDay()])
|
||||
->get(['id', 'folder', 'subject', 'outcome', 'handled_at']);
|
||||
$real = $leads->where('folder', Lead::INBOX);
|
||||
|
||||
$subjects = [];
|
||||
|
||||
foreach ($real->groupBy(fn (Lead $lead) => $lead->subject ?: __('Something else')) as $name => $group) {
|
||||
$subjects[] = ['name' => (string) $name, 'count' => $group->count()];
|
||||
}
|
||||
|
||||
usort($subjects, fn (array $a, array $b) => $b['count'] <=> $a['count'] ?: strcmp($a['name'], $b['name']));
|
||||
|
||||
return [
|
||||
'count' => $real->count(),
|
||||
'won' => $real->where('outcome', Lead::WON)->count(),
|
||||
'waiting' => $real->whereNull('handled_at')->count(),
|
||||
'kept_away' => $leads->count() - $real->count(),
|
||||
'subjects' => array_slice($subjects, 0, 8),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* One thing an account can be allowed to do. A group holds a list of these values;
|
||||
* a module declares the ones it adds (Module::permissions()).
|
||||
*/
|
||||
final readonly class Permission
|
||||
{
|
||||
/**
|
||||
* @param string $value `<module>.<action>`, also the name of the gate
|
||||
* @param string $label what the group form says next to the tick box
|
||||
* @param string $section the heading it is listed under
|
||||
* @param list<string> $needs values this one is useless without; a group that gets this gets those too
|
||||
*/
|
||||
public function __construct(
|
||||
public string $value,
|
||||
public string $label,
|
||||
public string $section,
|
||||
public array $needs = [],
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Permissions;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Support\Collection;
|
||||
use IriksIT\Manager\Contracts\PermissionResolver;
|
||||
|
||||
/**
|
||||
* For a site whose accounts have a role (a `role` column, or a `roles` list or relation): config `manager.permissions.roles` says
|
||||
* what each role may do, e.g. `['editor' => ['posts.view', 'posts.write'], 'owner' => ['*']]` (`*` is everything). The attribute is
|
||||
* `manager.permissions.role_attribute`.
|
||||
*/
|
||||
final class RoleMap implements PermissionResolver
|
||||
{
|
||||
public function permissions(Authenticatable $user): array
|
||||
{
|
||||
$roles = $user->{(string) config('manager.permissions.role_attribute', 'role')} ?? [];
|
||||
$roles = $roles instanceof Collection ? $roles->all() : (array) $roles;
|
||||
$map = (array) config('manager.permissions.roles', []);
|
||||
$out = [];
|
||||
|
||||
foreach ($roles as $role) {
|
||||
$name = is_object($role) ? (string) ($role->name ?? '') : (string) (is_scalar($role) ? $role : '');
|
||||
|
||||
foreach ((array) ($map[$name] ?? []) as $permission) {
|
||||
$out[] = (string) $permission;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($out));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Permissions;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use IriksIT\Manager\Contracts\PermissionResolver;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* What an account may do comes from the groups of the package (the default), from the roles of the site, or from both:
|
||||
* `manager.permissions.mode` is `groups`, `host` or `merge`. A site's side is its own `resolver` class, or the built-in `RoleMap`
|
||||
* when `roles` is filled. A super admin always may everything.
|
||||
*/
|
||||
final class Sources
|
||||
{
|
||||
public static function usesGroups(): bool
|
||||
{
|
||||
return self::mode() !== 'host';
|
||||
}
|
||||
|
||||
/** @return list<string> what the roles of the site allow (empty in `groups` mode) */
|
||||
public static function fromHost(Authenticatable $user): array
|
||||
{
|
||||
if (self::mode() === 'groups') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$class = config('manager.permissions.resolver');
|
||||
$resolver = is_string($class) && is_subclass_of($class, PermissionResolver::class) ? app($class) : (config('manager.permissions.roles') ? new RoleMap : null);
|
||||
|
||||
if ($resolver === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$known = app(ModuleRegistry::class)->permissionValues();
|
||||
$given = $resolver->permissions($user);
|
||||
|
||||
return in_array('*', $given, true) ? $known : array_values(array_filter($given, fn ($value) => is_string($value) && in_array($value, $known, true)));
|
||||
}
|
||||
|
||||
private static function mode(): string
|
||||
{
|
||||
return in_array(config('manager.permissions.mode'), ['groups', 'host', 'merge'], true) ? config('manager.permissions.mode') : 'groups';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* Ready-made definitions for `manager.resources` of the lists a business site nearly always has: services, projects,
|
||||
* reviews (testimonials), a menu and social links, and for `manager.pages.definitions` the business details. They are plain arrays, so a site changes what it wants:
|
||||
*
|
||||
* 'resources' => [
|
||||
* 'services' => Presets::services(['model' => App\Models\Service::class, 'feature' => 'services']),
|
||||
* 'projects' => Presets::projects(['model' => App\Models\Project::class, 'feature' => 'projects'], serviceModel: App\Models\Service::class),
|
||||
* ],
|
||||
*
|
||||
* Without `model` the records are kept in the package's own table. The field keys are the column names of the
|
||||
* usual site tables (`title`, `summary`, `is_active`, `sort_order`), so a site that has such tables points `model` at them.
|
||||
*/
|
||||
final class Presets
|
||||
{
|
||||
/** What the simple face says for each field of a preset, in plain words. */
|
||||
private const SIMPLE = [
|
||||
'services' => [
|
||||
'title' => ['label' => 'Name of the service', 'help' => 'What you call it, for example "Roof extensions".'],
|
||||
'summary' => ['label' => 'Short description', 'help' => 'One sentence that shows under the name.'],
|
||||
'body' => ['label' => 'The full story', 'help' => 'What you do and how you work. This is the text on the page of this service.'],
|
||||
'photo' => ['label' => 'Main photo'],
|
||||
'points' => ['label' => 'What you do', 'help' => 'Short lines, one per line.'],
|
||||
'faq' => ['label' => 'Questions people ask', 'help' => 'Add the questions you hear often, with your answer.'],
|
||||
'is_active' => ['label' => 'Show this on my website'],
|
||||
],
|
||||
'projects' => [
|
||||
'title' => ['label' => 'Name of the job', 'help' => 'For example "New kitchen in a farmhouse".'],
|
||||
'service_id' => ['label' => 'What kind of work was it?'],
|
||||
'place' => ['label' => 'Town', 'help' => 'The town only, never the street.'],
|
||||
'year' => ['label' => 'Year it was finished'],
|
||||
'story' => ['label' => 'What happened', 'help' => 'A few sentences about the job. Leave an empty line between paragraphs.'],
|
||||
'photo' => ['label' => 'Main photo'],
|
||||
'photos_agreed' => ['label' => 'The customer said these photos may be on the website'],
|
||||
'on_home' => ['label' => 'Show this on the home page'],
|
||||
'is_active' => ['label' => 'Show this on my website'],
|
||||
],
|
||||
'testimonials' => [
|
||||
'name' => ['label' => 'Who said it'],
|
||||
'role' => ['label' => 'Where they live or what they do', 'help' => 'For example "Utrecht" or "owner of a bakery".'],
|
||||
'quote' => ['label' => 'What they said', 'help' => 'Their words, as they gave them.'],
|
||||
'is_active' => ['label' => 'Show this on my website'],
|
||||
],
|
||||
'menu' => [
|
||||
'label' => ['label' => 'What the button says'],
|
||||
'url' => ['label' => 'Where it goes', 'help' => 'A page of your website, like /contact, or a full web address.'],
|
||||
'opens_new_tab' => ['label' => 'Open it in a new tab'],
|
||||
'is_active' => ['label' => 'Show this on my website'],
|
||||
],
|
||||
'socials' => [
|
||||
'label' => ['label' => 'Name', 'help' => 'For example "Facebook".'],
|
||||
'url' => ['label' => 'Web address of your page'],
|
||||
'is_active' => ['label' => 'Show this on my website'],
|
||||
],
|
||||
'business' => [
|
||||
'name' => ['label' => 'Name of your business'],
|
||||
'owner' => ['label' => 'Your first name', 'help' => 'Used on buttons such as "Call Alex".'],
|
||||
'phone' => ['label' => 'Your phone number', 'help' => 'As you want people to read it. It shows on every page, and behind the Call button.'],
|
||||
'whatsapp' => ['label' => 'Your WhatsApp number', 'help' => 'Leave it empty and there are no WhatsApp buttons on the website.'],
|
||||
'email' => ['label' => 'Your mail address', 'help' => 'It is never printed on the website, so spammers cannot find it. A visitor gets it by pressing a button.'],
|
||||
'street' => ['label' => 'Street and number'],
|
||||
'kvk' => ['label' => 'Chamber of Commerce number'],
|
||||
'vat' => ['label' => 'VAT number', 'help' => 'As on your invoices. Not sure? Leave it empty.'],
|
||||
'opening_hours' => ['label' => 'When people can reach you', 'help' => 'One line per day or group of days, as you want it read.'],
|
||||
'towns' => ['label' => 'Towns where you work', 'help' => 'One town per line.'],
|
||||
],
|
||||
];
|
||||
|
||||
/** What the simple face calls a list as a whole. */
|
||||
private const SIMPLE_NAMES = [
|
||||
'testimonials' => ['label' => 'What customers say', 'singular' => 'Customer review'],
|
||||
'projects' => ['label' => 'Our jobs', 'singular' => 'Job'],
|
||||
'menu' => ['label' => 'Buttons at the top', 'singular' => 'Button'],
|
||||
'socials' => ['label' => 'Your pages on other sites', 'singular' => 'Link'],
|
||||
'business' => ['title' => 'About your business'],
|
||||
];
|
||||
|
||||
/** @param array<string, mixed> $override */
|
||||
public static function services(array $override = []): array
|
||||
{
|
||||
return self::make('services', [
|
||||
'label' => 'Services', 'singular' => 'Service', 'hint' => 'What you do, each with a page of its own',
|
||||
'columns' => ['title', 'summary', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => [
|
||||
'title' => ['label' => 'Title', 'type' => 'text', 'required' => true],
|
||||
'slug' => ['label' => 'Address', 'type' => 'slug', 'from' => 'title', 'required' => true],
|
||||
'summary' => ['label' => 'One line for a card', 'type' => 'text', 'max' => 300],
|
||||
'body' => ['label' => 'Text of the page', 'type' => 'markdown'],
|
||||
'photo' => ['label' => 'Photo', 'type' => 'media'],
|
||||
'gallery' => ['label' => 'More photos', 'type' => 'media_list', 'advanced' => true],
|
||||
'points' => ['label' => 'What we do', 'type' => 'list', 'help' => 'Short lines.'],
|
||||
'faq' => ['label' => 'Questions and answers', 'type' => 'repeater', 'items' => self::questionItems()],
|
||||
'meta_description' => ['label' => 'Description for search engines', 'type' => 'text', 'max' => 300, 'advanced' => true],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $override
|
||||
* @param ?class-string $serviceModel the model of the services, to pick the kind of work a project belongs to
|
||||
*/
|
||||
public static function projects(array $override = [], ?string $serviceModel = null): array
|
||||
{
|
||||
$fields = [
|
||||
'title' => ['label' => 'Title', 'type' => 'text', 'required' => true],
|
||||
'slug' => ['label' => 'Address', 'type' => 'slug', 'from' => 'title', 'required' => true],
|
||||
];
|
||||
|
||||
if ($serviceModel !== null) {
|
||||
$fields['service_id'] = ['label' => 'Kind of work', 'type' => 'select', 'source' => ['model' => $serviceModel, 'label' => 'title', 'value' => 'id']];
|
||||
}
|
||||
|
||||
return self::make('projects', [
|
||||
'label' => 'Projects', 'singular' => 'Project', 'hint' => 'Finished jobs, with photos',
|
||||
'columns' => ['title', 'place', 'year', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => $fields + [
|
||||
'place' => ['label' => 'Town', 'type' => 'text', 'max' => 120, 'help' => 'The town only, never a street.'],
|
||||
'year' => ['label' => 'Year', 'type' => 'number'],
|
||||
'story' => ['label' => 'Story', 'type' => 'textarea', 'help' => 'A few sentences, paragraphs separated by a blank line.'],
|
||||
'photo' => ['label' => 'Photo', 'type' => 'media'],
|
||||
'gallery' => ['label' => 'More photos', 'type' => 'media_list', 'advanced' => true],
|
||||
'before_photo' => ['label' => 'Photo before', 'type' => 'media', 'advanced' => true],
|
||||
'after_photo' => ['label' => 'Photo after', 'type' => 'media', 'advanced' => true],
|
||||
'photos_agreed' => ['label' => 'The customer agreed to these photos on the site', 'type' => 'toggle', 'default' => false],
|
||||
'on_home' => ['label' => 'Show on the home page', 'type' => 'toggle', 'default' => false],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $override */
|
||||
public static function testimonials(array $override = []): array
|
||||
{
|
||||
return self::make('testimonials', [
|
||||
'label' => 'Reviews', 'singular' => 'Review', 'hint' => 'What customers say about you',
|
||||
'columns' => ['name', 'role', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => [
|
||||
'name' => ['label' => 'Name', 'type' => 'text', 'required' => true],
|
||||
'role' => ['label' => 'Place or function', 'type' => 'text'],
|
||||
'quote' => ['label' => 'What they said', 'type' => 'textarea', 'required' => true],
|
||||
'photo' => ['label' => 'Photo', 'type' => 'media', 'advanced' => true],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/**
|
||||
* Work and projects of a person or a company, for a CV or "about" page: a title, role, period, a story, points, links and
|
||||
* the technology used. `type` says which kind of entry it is (`work` or `project`; the site may offer other kinds with
|
||||
* `$override['fields']['type']['options']`).
|
||||
*
|
||||
* @param array<string, mixed> $override
|
||||
*/
|
||||
public static function experience(array $override = []): array
|
||||
{
|
||||
return self::make('experience', [
|
||||
'label' => 'Experience', 'singular' => 'Experience', 'hint' => 'Work and projects for the CV',
|
||||
'columns' => ['title', 'type', 'period', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => [
|
||||
'type' => ['label' => 'Kind', 'type' => 'select', 'required' => true, 'default' => 'work', 'options' => ['work' => 'Work', 'project' => 'Project']],
|
||||
'title' => ['label' => 'Title', 'type' => 'text', 'required' => true],
|
||||
'role' => ['label' => 'Role', 'type' => 'text'],
|
||||
'period' => ['label' => 'Period', 'type' => 'text', 'max' => 60, 'help' => 'As it should be read, for example 2021 - now.'],
|
||||
'summary' => ['label' => 'One line', 'type' => 'text'],
|
||||
'story' => ['label' => 'Story', 'type' => 'textarea', 'help' => 'A few sentences, paragraphs separated by a blank line.'],
|
||||
'bullets' => ['label' => 'Points', 'type' => 'list'],
|
||||
'links' => ['label' => 'Links', 'type' => 'repeater', 'items' => ['label' => ['label' => 'Text', 'type' => 'text'], 'url' => ['label' => 'Address', 'type' => 'url']]],
|
||||
'tech' => ['label' => 'Technology', 'type' => 'list'],
|
||||
'on_cv' => ['label' => 'Show on the CV', 'type' => 'toggle', 'default' => true],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $override */
|
||||
public static function menu(array $override = []): array
|
||||
{
|
||||
return self::make('menu', [
|
||||
'label' => 'Menu', 'singular' => 'Menu item', 'hint' => 'The links at the top of the site',
|
||||
'columns' => ['label', 'url', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => [
|
||||
'label' => ['label' => 'Text', 'type' => 'text', 'required' => true],
|
||||
'url' => ['label' => 'Address', 'type' => 'text', 'required' => true, 'help' => 'A page of your site (/contact) or a full address.'],
|
||||
'opens_new_tab' => ['label' => 'Opens in a new tab', 'type' => 'toggle', 'default' => false],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $override */
|
||||
public static function socials(array $override = []): array
|
||||
{
|
||||
return self::make('socials', [
|
||||
'label' => 'Social links', 'singular' => 'Link', 'hint' => 'Your pages on other sites',
|
||||
'columns' => ['label', 'url', 'is_active'], 'order' => ['sort_order', 'asc'],
|
||||
'fields' => [
|
||||
'label' => ['label' => 'Name', 'type' => 'text', 'required' => true],
|
||||
'url' => ['label' => 'Address', 'type' => 'url', 'required' => true],
|
||||
'icon' => ['label' => 'Icon', 'type' => 'text', 'advanced' => true],
|
||||
'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0],
|
||||
'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/**
|
||||
* The page "Business details" for `manager.pages.definitions['business']`: what the site says about the business in its
|
||||
* header, footer, contact page and legal pages. Entered once, read with `Page::contentFor('business')`. The address for
|
||||
* visitors and the address where requests are mailed to are not meant to be printed in a page.
|
||||
*
|
||||
* @param array<string, mixed> $override `title` and `fields` (merged per field)
|
||||
* @return array{title: string, fields: array<string, array<string, mixed>>}
|
||||
*/
|
||||
public static function business(array $override = []): array
|
||||
{
|
||||
return self::make('business', [
|
||||
'title' => 'Business details',
|
||||
'fields' => [
|
||||
'name' => ['label' => 'Name of the business', 'type' => 'text'],
|
||||
'owner' => ['label' => 'Owner', 'type' => 'text', 'help' => 'The first name is used on buttons such as "Call Alex".'],
|
||||
'phone' => ['label' => 'Phone number', 'type' => 'text', 'help' => 'As it should be read, for example 06 12 34 56 78. Shown on every page.'],
|
||||
'whatsapp' => ['label' => 'WhatsApp number', 'type' => 'text', 'help' => 'Leave empty to leave the WhatsApp buttons off the site.'],
|
||||
'email' => ['label' => 'Mail address for visitors', 'type' => 'text', 'help' => 'Never printed in a page: a visitor gets it by pressing a button.'],
|
||||
'street' => ['label' => 'Street and number', 'type' => 'text'],
|
||||
'postcode' => ['label' => 'Postcode', 'type' => 'text'],
|
||||
'city' => ['label' => 'Town', 'type' => 'text'],
|
||||
'kvk' => ['label' => 'Chamber of Commerce number', 'type' => 'text'],
|
||||
'vat' => ['label' => 'VAT number', 'type' => 'text', 'help' => 'As on your invoices. Leave empty when you are not sure.'],
|
||||
'opening_hours' => ['label' => 'Opening hours', 'type' => 'lines', 'help' => 'One line per day or group of days, as it should be read.'],
|
||||
'towns' => ['label' => 'Work area: the towns', 'type' => 'lines', 'help' => 'One per line.'],
|
||||
'maps_url' => ['label' => 'Link to the map', 'type' => 'url'],
|
||||
],
|
||||
], $override);
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private static function questionItems(): array
|
||||
{
|
||||
return ['question' => ['label' => 'Question', 'type' => 'text'], 'answer' => ['label' => 'Answer', 'type' => 'textarea']];
|
||||
}
|
||||
|
||||
/**
|
||||
* What the site sets wins; `fields` are merged per field, so one field can change without the rest.
|
||||
*
|
||||
* @param array<string, mixed> $preset
|
||||
* @param array<string, mixed> $override
|
||||
*/
|
||||
private static function make(string $name, array $preset, array $override): array
|
||||
{
|
||||
// The words of the simple face, for someone who is not a webmaster; a site overrides them like any other field.
|
||||
foreach (self::SIMPLE[$name] ?? [] as $key => $simple) {
|
||||
if (isset($preset['fields'][$key])) {
|
||||
$preset['fields'][$key]['simple'] = $simple;
|
||||
}
|
||||
}
|
||||
$preset['simple'] = self::SIMPLE_NAMES[$name] ?? [];
|
||||
$fields = array_replace_recursive($preset['fields'], (array) ($override['fields'] ?? []));
|
||||
unset($override['fields']);
|
||||
|
||||
return [...$preset, ...$override, 'fields' => $fields];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use IriksIT\Manager\Models\Record;
|
||||
|
||||
/**
|
||||
* The resources of the site (config `manager.resources`): lists of records the screens make a form for,
|
||||
* without code of the site's own. A resource is its fields (see `Fields`) plus where they are kept: in a
|
||||
* model of the site (`model`, the field keys are its attributes) or, without one, in the package's own
|
||||
* table of records.
|
||||
*
|
||||
* 'services' => ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class,
|
||||
* 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => [...]]
|
||||
*/
|
||||
final class Resources
|
||||
{
|
||||
/** Names the permissions of modules that exist already would clash with. */
|
||||
private const RESERVED = ['posts', 'pages', 'media', 'accounts', 'groups', 'audit', 'statistics', 'reviews', 'labels', 'profile', 'manager', 'records'];
|
||||
|
||||
/**
|
||||
* @return array<string, array{key: string, label: string, singular: string, simple_label: ?string, simple_singular: ?string, model: ?string, fields: array<string, array<string, mixed>>, columns: list<string>, order: array{0: string, 1: string}, per_page: int}>
|
||||
*/
|
||||
public static function all(): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ((array) config('manager.resources', []) as $key => $definition) {
|
||||
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || in_array($key, self::RESERVED, true) || ! is_array($definition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A resource of a feature that is switched off is not there: no menu item, no permissions, no screens.
|
||||
if (isset($definition['feature']) && ! Features::on((string) $definition['feature'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = Fields::normalize((array) ($definition['fields'] ?? []));
|
||||
$model = $definition['model'] ?? null;
|
||||
$columns = array_values(array_filter((array) ($definition['columns'] ?? array_slice(array_keys($fields), 0, 3)), fn ($column) => isset($fields[$column])));
|
||||
$order = (array) ($definition['order'] ?? []);
|
||||
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null,
|
||||
'singular' => (string) ($definition['singular'] ?? $definition['label'] ?? $key),
|
||||
'simple_label' => Fields::simpleText($definition, 'label'),
|
||||
'simple_singular' => Fields::simpleText($definition, 'singular'),
|
||||
'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null,
|
||||
'fields' => $fields,
|
||||
// A page layout for the page of one record: `true` for every block type, or a list of the types it may use.
|
||||
'template' => ($definition['template'] ?? false) === true ? true : (is_array($definition['template'] ?? null) ? array_values(array_filter($definition['template'], 'is_string')) : false),
|
||||
'columns' => $columns,
|
||||
'order' => [preg_match('/^[a-z_][a-z0-9_]*$/', (string) ($order[0] ?? '')) ? (string) $order[0] : 'id', ($order[1] ?? 'desc') === 'asc' ? 'asc' : 'desc'],
|
||||
'per_page' => max(5, min(200, (int) ($definition['per_page'] ?? 50))),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @return ?array<string, mixed> */
|
||||
public static function find(string $key): ?array
|
||||
{
|
||||
return self::all()[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $resource
|
||||
* @return Builder<Eloquent>
|
||||
*/
|
||||
public static function query(array $resource): Builder
|
||||
{
|
||||
[$column, $direction] = $resource['order'];
|
||||
|
||||
if ($resource['model'] !== null) {
|
||||
return $resource['model']::query()->orderBy($column, $direction)->orderBy('id', 'desc');
|
||||
}
|
||||
|
||||
// The package's own table keeps the values in one JSON column.
|
||||
$query = Record::query()->where('resource', $resource['key']);
|
||||
|
||||
return $column !== 'id' && isset($resource['fields'][$column]) ? $query->orderBy('data->'.$column, $direction) : $query->orderBy('id', $column === 'id' ? $direction : 'desc');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $resource
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function row(array $resource, Eloquent $model): array
|
||||
{
|
||||
$stored = $resource['model'] === null ? (array) $model->getAttribute('data') : null;
|
||||
$values = [];
|
||||
|
||||
foreach ($resource['fields'] as $key => $field) {
|
||||
$values[$key] = $stored !== null ? ($stored[$key] ?? $field['default']) : ($model->getAttribute($key) ?? $field['default']);
|
||||
}
|
||||
|
||||
return ['id' => $model->getKey(), 'values' => $values];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $resource
|
||||
* @param array<string, mixed> $values cleaned by `Fields::clean`
|
||||
*/
|
||||
public static function save(array $resource, ?Eloquent $model, array $values): Eloquent
|
||||
{
|
||||
if ($resource['model'] === null) {
|
||||
$model ??= new Record(['resource' => $resource['key']]);
|
||||
$model->data = $values;
|
||||
} else {
|
||||
$model ??= new $resource['model'];
|
||||
// Only the keys the site defined: the definition is the whitelist.
|
||||
$model->forceFill($values);
|
||||
}
|
||||
|
||||
$model->save();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $resource
|
||||
*/
|
||||
public static function record(array $resource, int|string $id): ?Eloquent
|
||||
{
|
||||
return self::query($resource)->reorder()->whereKey($id)->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model as Eloquent;
|
||||
use IriksIT\Manager\Models\Page;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Revision;
|
||||
|
||||
/**
|
||||
* The history of what people write: every save of a post or a page keeps its state, and an earlier state can be put back
|
||||
* (which is a save, so it is in the history too). A site adds its own models in config `manager.revisions.types`.
|
||||
*
|
||||
* 'types' => ['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']]
|
||||
*/
|
||||
final class Revisions
|
||||
{
|
||||
/** How many states are kept per record unless config `manager.revisions.keep` says otherwise. */
|
||||
private const KEEP = 50;
|
||||
|
||||
/**
|
||||
* What has a history: key => model, the permissions to see and to put back, the attributes that are not part of it (for a
|
||||
* post that is whether it is on the site: going back in time must not publish or hide anything).
|
||||
*
|
||||
* @return array<string, array{model: class-string<Eloquent>, view: string, restore: string, except: list<string>}>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
$types = [
|
||||
'posts' => ['model' => Post::class, 'view' => 'posts.view', 'restore' => 'posts.write', 'except' => ['published_at']],
|
||||
'pages' => ['model' => Page::class, 'view' => 'pages.edit', 'restore' => 'pages.edit', 'except' => ['is_published']],
|
||||
];
|
||||
|
||||
foreach ((array) config('manager.revisions.types', []) as $key => $type) {
|
||||
if (is_string($key) && preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) && is_array($type) && is_subclass_of($type['model'] ?? '', Eloquent::class)) {
|
||||
$types[$key] = ['model' => $type['model'], 'view' => (string) ($type['view'] ?? $key.'.view'), 'restore' => (string) ($type['restore'] ?? $key.'.manage'), 'except' => array_values((array) ($type['except'] ?? []))];
|
||||
}
|
||||
}
|
||||
|
||||
return array_filter($types, fn (array $type) => ! in_array($type['model'], (array) config('manager.revisions.skip', []), true));
|
||||
}
|
||||
|
||||
/** Starts keeping the history of every type: a save of a record writes its state, a delete removes its history. */
|
||||
public static function listen(): void
|
||||
{
|
||||
foreach (self::types() as $key => $type) {
|
||||
$type['model']::saved(fn (Eloquent $model) => self::record($key, $model));
|
||||
$type['model']::deleted(fn (Eloquent $model) => Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->delete());
|
||||
}
|
||||
}
|
||||
|
||||
public static function record(string $key, Eloquent $model): ?Revision
|
||||
{
|
||||
$type = self::types()[$key] ?? null;
|
||||
|
||||
if ($type === null || ! $model->getKey()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = self::snapshot($model, $type['except']);
|
||||
$latest = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->first();
|
||||
|
||||
if ($latest !== null && $latest->data == $data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$user = auth()->user();
|
||||
$revision = Revision::query()->create([
|
||||
'type' => $key,
|
||||
'subject_id' => $model->getKey(),
|
||||
'user_id' => $user?->getAuthIdentifier(),
|
||||
'user_name' => $user === null ? null : mb_substr((string) ($user->name ?? ''), 0, 255),
|
||||
'data' => $data,
|
||||
'changed' => $latest === null ? array_keys($data) : self::changed((array) $latest->data, $data),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
// Keep the newest ones only.
|
||||
$old = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->skip(max(5, (int) config('manager.revisions.keep', self::KEEP)))->take(1000)->pluck('id');
|
||||
$old->isNotEmpty() && Revision::query()->whereKey($old)->delete();
|
||||
|
||||
return $revision;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a state back. It is a save like any other, so the history shows it and the state before it is not lost.
|
||||
*
|
||||
* @param array{except: list<string>} $type
|
||||
*/
|
||||
public static function restore(Eloquent $model, Revision $revision, array $type): Eloquent
|
||||
{
|
||||
$keep = array_flip([...$type['except'], $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]);
|
||||
$model->forceFill(array_diff_key((array) $revision->data, $keep))->save();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $except
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function snapshot(Eloquent $model, array $except): array
|
||||
{
|
||||
$skip = array_flip([...$except, $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]);
|
||||
|
||||
return array_diff_key($model->attributesToArray(), $skip);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function changed(array $before, array $after): array
|
||||
{
|
||||
return array_values(array_filter(array_keys($after + $before), fn ($key) => ($before[$key] ?? null) != ($after[$key] ?? null)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use IriksIT\Manager\Exceptions\MediaStorageException;
|
||||
use IriksIT\Manager\Support\IriksStorage\Client;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The "try it" buttons of the settings screen: one check per group of settings that makes a connection (the IriksIT API, Turnstile).
|
||||
* A check uses what is saved, never what is typed but not yet saved, and says in one line whether it works. A site adds its own in
|
||||
* `manager.settings.checks` as `'Group name' => SomeClass::class`, a class with an `__invoke(): string` that returns what worked
|
||||
* (for example "Connected") and throws when it did not (the message is shown as it is, so keep secrets out of it).
|
||||
*/
|
||||
class Checks
|
||||
{
|
||||
/** @return array<string, class-string|callable> group name (as in the definitions) => check */
|
||||
public function all(): array
|
||||
{
|
||||
return [
|
||||
'IriksIT API' => fn () => $this->iriksit(),
|
||||
'Login' => fn () => $this->turnstile(),
|
||||
...array_filter((array) config('manager.settings.checks', []), fn ($check) => is_string($check) && class_exists($check)),
|
||||
];
|
||||
}
|
||||
|
||||
public function has(string $group): bool
|
||||
{
|
||||
return array_key_exists($group, $this->all());
|
||||
}
|
||||
|
||||
/** @return array{ok: bool, message: string} */
|
||||
public function run(string $group): array
|
||||
{
|
||||
$check = $this->all()[$group] ?? null;
|
||||
|
||||
if ($check === null) {
|
||||
return ['ok' => false, 'message' => __('There is nothing to try here.')];
|
||||
}
|
||||
|
||||
try {
|
||||
return ['ok' => true, 'message' => (string) (is_string($check) ? app($check)() : $check())];
|
||||
} catch (Throwable $e) {
|
||||
return ['ok' => false, 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
private function iriksit(): string
|
||||
{
|
||||
$client = new Client((array) config('manager.media.iriksit', []));
|
||||
|
||||
if (! $client->isConfigured()) {
|
||||
throw new \RuntimeException(__('The address, the account and the password are not all filled in.'));
|
||||
}
|
||||
|
||||
try {
|
||||
$client->check();
|
||||
} catch (MediaStorageException $e) {
|
||||
throw new \RuntimeException(__('Logging in at the IriksIT API failed:').' '.$e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
return __('Logged in at the IriksIT API.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare answers a known secret with "invalid-input-response" for a made-up token, and an unknown one with "invalid-input-secret":
|
||||
* that tells the secret without needing a real visitor.
|
||||
*/
|
||||
private function turnstile(): string
|
||||
{
|
||||
$secret = (string) config('manager.login.turnstile.secret');
|
||||
|
||||
if ($secret === '' || (string) config('manager.login.turnstile.site_key') === '') {
|
||||
throw new \RuntimeException(__('Turnstile is off: the site key and the secret are not both filled in.'));
|
||||
}
|
||||
|
||||
$answer = Http::asForm()->timeout(8)->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', ['secret' => $secret, 'response' => 'manager-check']);
|
||||
$codes = (array) $answer->json('error-codes', []);
|
||||
|
||||
if (in_array('invalid-input-secret', $codes, true) || in_array('missing-input-secret', $codes, true)) {
|
||||
throw new \RuntimeException(__('Cloudflare does not know this secret key.'));
|
||||
}
|
||||
|
||||
if (! $answer->ok()) {
|
||||
throw new \RuntimeException(__('Cloudflare did not answer properly.'));
|
||||
}
|
||||
|
||||
return __('Cloudflare knows this secret key.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use IriksIT\Manager\Support\Features;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/**
|
||||
* What can be set from the settings screen. A definition is keyed by the config path it overrides (`manager.modules.reviews`)
|
||||
* and has: `label`, `type` (toggle, text, url, number, select, secret), `group`, optional `help`, `options` (select: value => label),
|
||||
* `env` (the .env variable that is written along when the site allows it) and `permission` (a right on top of `settings.manage`).
|
||||
* A secret is never sent back to a browser.
|
||||
*
|
||||
* They come from three places: the parts of the manager, the integrations the package knows (Turnstile, the IriksIT API) and
|
||||
* the site itself (`manager.settings.definitions`, and `settings()` of a module of its own). Nothing else can be set: a key that
|
||||
* is not defined is refused, so the screen can never write an arbitrary setting or .env line.
|
||||
*/
|
||||
class Definitions
|
||||
{
|
||||
public const TYPES = ['toggle', 'text', 'url', 'number', 'select', 'secret'];
|
||||
|
||||
public function __construct(private readonly ModuleRegistry $modules) {}
|
||||
|
||||
/** @return array<string, array<string, mixed>> keyed by config path */
|
||||
public function all(): array
|
||||
{
|
||||
$all = [];
|
||||
|
||||
foreach ([...$this->parts(), ...$this->features(), ...$this->frontend(), ...$this->integrations(), ...$this->fromModules(), ...(array) config('manager.settings.definitions', [])] as $key => $definition) {
|
||||
$key = is_string($key) ? $key : (string) ($definition['config'] ?? '');
|
||||
$definition = $this->normalise($key, (array) $definition);
|
||||
|
||||
if ($definition !== null) {
|
||||
$all[$key] = $definition;
|
||||
}
|
||||
}
|
||||
|
||||
return $all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns what was typed into the value of the setting, or says it is no good.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function cast(array $definition, mixed $raw): mixed
|
||||
{
|
||||
$bad = fn () => throw new \InvalidArgumentException('This value is not valid.');
|
||||
|
||||
return match ($definition['type']) {
|
||||
'toggle' => is_bool($raw) || in_array($raw, [0, 1, '0', '1', 'true', 'false'], true) ? filter_var($raw, FILTER_VALIDATE_BOOLEAN) : $bad(),
|
||||
'number' => is_numeric($raw) ? $raw + 0 : $bad(),
|
||||
'select' => is_string($raw) && array_key_exists($raw, $definition['options']) ? $raw : $bad(),
|
||||
'url' => is_string($raw) && mb_strlen($raw) <= 500 && preg_match('#^https?://[^\s<>"\']+$#i', $raw) === 1 ? $raw : $bad(),
|
||||
default => is_string($raw) && mb_strlen($raw) <= 1000 && preg_match('/[\r\n\0]/', $raw) !== 1 ? trim($raw) : $bad(),
|
||||
};
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function find(string $key): ?array
|
||||
{
|
||||
return $this->all()[$key] ?? null;
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function parts(): array
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach ($this->modules->all() as $module) {
|
||||
// Users and media are the core: without them there is no manager.
|
||||
if (in_array($module->key(), ['users', 'media', 'settings'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A feature of the site with the name of the module is its switch: it has its own toggle.
|
||||
if (isset(Features::all()[$module->key()])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts['manager.modules.'.$module->key()] = [
|
||||
'label' => $module->label(),
|
||||
'type' => 'toggle',
|
||||
'group' => 'Parts of the manager',
|
||||
'env' => 'MANAGER_'.strtoupper($module->key()),
|
||||
];
|
||||
}
|
||||
|
||||
return $parts;
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function features(): array
|
||||
{
|
||||
$features = [];
|
||||
|
||||
foreach (Features::all() as $key => $feature) {
|
||||
$features['manager.features.'.$key.'.enabled'] = [
|
||||
'label' => $feature['label'],
|
||||
'type' => 'toggle',
|
||||
'group' => 'Features of the site',
|
||||
'help' => $feature['hint'],
|
||||
'env' => $feature['env'],
|
||||
];
|
||||
}
|
||||
|
||||
return $features;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who draws the site, in words an owner can follow. Only there when the pages module is on: without pages there is nothing to draw.
|
||||
*
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private function frontend(): array
|
||||
{
|
||||
if (array_filter($this->modules->active(), fn ($module) => $module->key() === 'pages') === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'manager.frontend.mode' => [
|
||||
'label' => 'Who shows the website',
|
||||
'type' => 'select',
|
||||
'group' => 'The website',
|
||||
'help' => 'The website itself (it has its own code, the usual choice), this manager (it draws every page made of blocks at its address, nothing else is needed), or another website that reads the pages from here (headless).',
|
||||
'options' => ['site' => 'The website itself', 'package' => 'This manager', 'headless' => 'Another website reads it (headless)'],
|
||||
'env' => 'MANAGER_FRONTEND',
|
||||
],
|
||||
'manager.blocks.preview.enabled' => [
|
||||
'label' => 'Show the real page next to the editor',
|
||||
'type' => 'toggle',
|
||||
'group' => 'The website',
|
||||
'help' => 'While you build a page you see how it looks on a phone, tablet and computer, before you save.',
|
||||
'env' => 'MANAGER_BLOCKS_PREVIEW',
|
||||
],
|
||||
'manager.blocks.api.enabled' => [
|
||||
'label' => 'Let another website read the pages',
|
||||
'type' => 'toggle',
|
||||
'group' => 'The website',
|
||||
'help' => 'The pages go out as data (JSON) for a website or app elsewhere. Always on when the website is "headless".',
|
||||
'env' => 'MANAGER_BLOCKS_API',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function integrations(): array
|
||||
{
|
||||
$disks = array_keys((array) config('filesystems.disks', []));
|
||||
|
||||
return [
|
||||
'manager.media.disk' => ['label' => 'Disk for new media files', 'type' => 'select', 'group' => 'Media', 'sensitive' => true, 'options' => array_combine($disks, $disks), 'env' => 'MANAGER_MEDIA_DISK'],
|
||||
'manager.media.iriksit.url' => ['label' => 'IriksIT API: address', 'type' => 'url', 'group' => 'IriksIT API', 'sensitive' => true, 'help' => 'With its version, for example https://api.iriks-it.nl/v1', 'env' => 'MANAGER_IRIKSIT_URL'],
|
||||
'manager.media.iriksit.email' => ['label' => 'IriksIT API: account', 'type' => 'text', 'group' => 'IriksIT API', 'sensitive' => true, 'env' => 'MANAGER_IRIKSIT_EMAIL'],
|
||||
'manager.media.iriksit.password' => ['label' => 'IriksIT API: password', 'type' => 'secret', 'group' => 'IriksIT API', 'env' => 'MANAGER_IRIKSIT_PASSWORD'],
|
||||
'manager.login.turnstile.site_key' => ['label' => 'Turnstile: site key', 'type' => 'text', 'group' => 'Login', 'sensitive' => true, 'env' => 'MANAGER_TURNSTILE_SITE_KEY'],
|
||||
'manager.login.turnstile.secret' => ['label' => 'Turnstile: secret key', 'type' => 'secret', 'group' => 'Login', 'env' => 'MANAGER_TURNSTILE_SECRET'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function fromModules(): array
|
||||
{
|
||||
$found = [];
|
||||
|
||||
foreach ($this->modules->active() as $module) {
|
||||
if (method_exists($module, 'settings')) {
|
||||
foreach ((array) $module->settings() as $key => $definition) {
|
||||
$found[$key] = $definition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null null when the definition is no good: it is left out, never half used */
|
||||
private function normalise(string $key, array $definition): ?array
|
||||
{
|
||||
$type = $definition['type'] ?? 'text';
|
||||
|
||||
if (preg_match('/^[a-z][a-z0-9_]*(\.[a-zA-Z0-9_-]+)+$/', $key) !== 1 || ! in_array($type, self::TYPES, true) || ! is_string($definition['label'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$env = $definition['env'] ?? null;
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'config' => $key,
|
||||
'label' => $definition['label'],
|
||||
'type' => $type,
|
||||
'group' => is_string($definition['group'] ?? null) ? $definition['group'] : 'Site',
|
||||
'help' => is_string($definition['help'] ?? null) ? $definition['help'] : null,
|
||||
'options' => $type === 'select' ? (array) ($definition['options'] ?? []) : [],
|
||||
'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null,
|
||||
'permission' => is_string($definition['permission'] ?? null) ? $definition['permission'] : null,
|
||||
// What can send a password or a file somewhere else (an address, an account, a disk) needs the right for secrets too, and the password of whoever saves it.
|
||||
'sensitive' => $type === 'secret' || (bool) ($definition['sensitive'] ?? false),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
/**
|
||||
* Writes variables into the .env file of the app, when the site allows it (`manager.settings.write_env`) and the file may be
|
||||
* written. Only variables that a definition names are ever written, and a value that could break the file (a line break, a
|
||||
* null byte) is refused. The file is rewritten as a whole: the old one is kept as `.env.manager-backup`, the new one is
|
||||
* written next to it and moved over in one step, with the permissions of the old one.
|
||||
*/
|
||||
class EnvFile
|
||||
{
|
||||
public function __construct(private readonly ?string $path = null) {}
|
||||
|
||||
public function path(): string
|
||||
{
|
||||
return $this->path ?? app()->environmentFilePath();
|
||||
}
|
||||
|
||||
public function writable(): bool
|
||||
{
|
||||
return is_file($this->path()) && is_writable($this->path()) && is_writable(dirname($this->path()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|int|float|bool|null> $pairs variable => value (null removes nothing: the line is left alone)
|
||||
*/
|
||||
public function set(array $pairs): bool
|
||||
{
|
||||
$pairs = array_filter($pairs, fn ($value) => $value !== null);
|
||||
|
||||
if ($pairs === [] || ! $this->writable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($pairs as $name => $value) {
|
||||
if (preg_match('/^[A-Z][A-Z0-9_]*$/', (string) $name) !== 1 || preg_match('/[\r\n\0]/', (string) $this->text($value)) === 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$lock = fopen($this->path().'.manager-lock', 'c');
|
||||
|
||||
if ($lock === false || ! flock($lock, LOCK_EX)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$old = (string) file_get_contents($this->path());
|
||||
$lines = preg_split('/\R/', $old) ?: [];
|
||||
$left = $pairs;
|
||||
|
||||
foreach ($lines as $i => $line) {
|
||||
if (preg_match('/^\s*([A-Z][A-Z0-9_]*)\s*=/', $line, $found) === 1 && array_key_exists($found[1], $left)) {
|
||||
$lines[$i] = $found[1].'='.$this->quote($left[$found[1]]);
|
||||
unset($left[$found[1]]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($left as $name => $value) {
|
||||
$lines[] = $name.'='.$this->quote($value);
|
||||
}
|
||||
|
||||
$new = rtrim(implode("\n", $lines), "\n")."\n";
|
||||
$temporary = $this->path().'.'.bin2hex(random_bytes(4)).'.tmp';
|
||||
|
||||
if (@copy($this->path(), $this->path().'.manager-backup') === false || @file_put_contents($temporary, $new) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@chmod($temporary, fileperms($this->path()) & 0777);
|
||||
|
||||
if (! @rename($temporary, $this->path())) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
|
||||
private function text(mixed $value): string
|
||||
{
|
||||
return is_bool($value) ? ($value ? 'true' : 'false') : (string) $value;
|
||||
}
|
||||
|
||||
private function quote(mixed $value): string
|
||||
{
|
||||
$text = $this->text($value);
|
||||
|
||||
if (preg_match('/^[A-Za-z0-9_.:\/@+,-]*$/', $text) === 1) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $text).'"';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* What was set from the settings screen. The table is the truth (with a history of who and when); every change also writes
|
||||
* one compiled file (`bootstrap/cache/manager-settings.php`, secrets in it stay encrypted) that is laid over the config
|
||||
* while the app starts, so a request reads one file from opcache and never asks the database. That works with `config:cache`
|
||||
* too, because it is applied after the config was loaded. Without the file (it could not be written) the table is read once.
|
||||
*/
|
||||
class Store
|
||||
{
|
||||
public function __construct(private readonly Definitions $definitions) {}
|
||||
|
||||
public static function file(): string
|
||||
{
|
||||
return app()->bootstrapPath('cache/manager-settings.php');
|
||||
}
|
||||
|
||||
/** Lays the saved settings over the config. Called while the provider registers; it must never fail the app. */
|
||||
public static function overlay(): void
|
||||
{
|
||||
try {
|
||||
$values = is_file(self::file()) ? (array) (include self::file()) : self::fromTable();
|
||||
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_array($value) && array_key_exists('__enc', $value)) {
|
||||
$value = json_decode(Crypt::decryptString((string) $value['__enc']), true);
|
||||
}
|
||||
|
||||
config([$key => $value]);
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// A missing table (before the first migrate), a changed APP_KEY, a broken file: the config keeps what it had.
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private static function fromTable(): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach (DB::table(Names::table('settings'))->get() as $row) {
|
||||
$values[$row->key] = $row->is_secret ? ['__enc' => $row->value] : json_decode((string) $row->value, true);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves values (null: back to what the config says) and rewrites the compiled file. Returns whether that file could be written.
|
||||
*
|
||||
* @param array<string, mixed> $values by config path, already checked against the definitions
|
||||
*/
|
||||
public function put(array $values, mixed $userId = null): bool
|
||||
{
|
||||
$table = Names::table('settings');
|
||||
|
||||
DB::transaction(function () use ($values, $table, $userId) {
|
||||
foreach ($values as $key => $value) {
|
||||
$definition = $this->definitions->find($key);
|
||||
|
||||
if ($value === null || $definition === null) {
|
||||
DB::table($table)->where('key', $key)->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$secret = $definition['type'] === 'secret';
|
||||
$stored = $secret ? Crypt::encryptString(json_encode($value)) : json_encode($value);
|
||||
|
||||
DB::table($table)->updateOrInsert(['key' => $key], ['value' => $stored, 'is_secret' => $secret, 'updated_by' => $userId, 'updated_at' => now(), 'created_at' => now()]);
|
||||
}
|
||||
});
|
||||
|
||||
return $this->compile();
|
||||
}
|
||||
|
||||
/** Writes the compiled file from the table: to a temporary file first, then moved over the old one in one step. */
|
||||
public function compile(): bool
|
||||
{
|
||||
$known = $this->definitions->all();
|
||||
$values = array_filter(self::fromTable(), fn ($value, $key) => isset($known[$key]), ARRAY_FILTER_USE_BOTH);
|
||||
$file = self::file();
|
||||
$temporary = $file.'.'.bin2hex(random_bytes(4)).'.tmp';
|
||||
|
||||
try {
|
||||
if (@file_put_contents($temporary, '<?php return '.var_export($values, true).';'.PHP_EOL, LOCK_EX) === false || ! @rename($temporary, $file)) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
} catch (Throwable) {
|
||||
@unlink($temporary);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function_exists('opcache_invalidate') && @opcache_invalidate($file, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether a setting has been saved here (and so wins over .env). */
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return DB::table(Names::table('settings'))->where('key', $key)->exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Settings;
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Throwable;
|
||||
|
||||
/** Saves changes to settings: the table and the compiled file, the config of this request, and `.env` when the site allows it. */
|
||||
class Writer
|
||||
{
|
||||
public function __construct(private readonly Definitions $definitions, private readonly Store $store, private readonly EnvFile $env) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes config path => value; null puts the setting back to what the config says
|
||||
* @return array{file_written: bool, env_written: bool}
|
||||
*/
|
||||
public function apply(array $changes, mixed $userId = null): array
|
||||
{
|
||||
if ($changes === []) {
|
||||
return ['file_written' => true, 'env_written' => false];
|
||||
}
|
||||
|
||||
$written = $this->store->put($changes, $userId);
|
||||
|
||||
foreach ($changes as $key => $value) {
|
||||
config([$key => $value ?? config($key)]);
|
||||
}
|
||||
|
||||
return ['file_written' => $written, 'env_written' => $this->writeEnv($changes)];
|
||||
}
|
||||
|
||||
/** Writes the compiled file again and empties what caches the old values. */
|
||||
public function refresh(): bool
|
||||
{
|
||||
$written = $this->store->compile();
|
||||
function_exists('opcache_reset') && @opcache_reset();
|
||||
$this->recache();
|
||||
|
||||
return $written;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $changes */
|
||||
private function writeEnv(array $changes): bool
|
||||
{
|
||||
if (! config('manager.settings.write_env')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pairs = [];
|
||||
|
||||
foreach ($changes as $key => $value) {
|
||||
$env = $this->definitions->find($key)['env'] ?? null;
|
||||
|
||||
if ($env !== null && $value !== null) {
|
||||
$pairs[$env] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$done = $this->env->set($pairs);
|
||||
$done && $this->recache();
|
||||
|
||||
return $done;
|
||||
}
|
||||
|
||||
private function recache(): void
|
||||
{
|
||||
if (! app()->configurationIsCached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Artisan::call('config:cache');
|
||||
} catch (Throwable) {
|
||||
// The overlay still applies on top of a config cache that is a bit old.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\PostShare;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Sharing posts on the platforms: doing it, and what came of it. The only code that writes `post_shares`.
|
||||
*
|
||||
* A site posts for real only with the setting `manager.sharing.live`. Without it (staging, local) a share is written down
|
||||
* as done, marked "dry run", and nothing is sent. A row moves from `pending` to `sharing` before the platform is called,
|
||||
* so two clicks can never post the same thing twice, and a failure stays failed until the owner presses the button again.
|
||||
*/
|
||||
final class PostSharing
|
||||
{
|
||||
public function __construct(private readonly Sharers $sharers) {}
|
||||
|
||||
public static function isLive(): bool
|
||||
{
|
||||
return config('manager.sharing.live') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shares a published post on one platform right now, also when it was shared there before.
|
||||
*
|
||||
* @throws SharingException when the post is not live or the platform is not connected
|
||||
*/
|
||||
public function shareNow(Post $post, string $platform): PostShare
|
||||
{
|
||||
if (! $post->isPublished()) {
|
||||
throw new SharingException(__('Only a post that is live can be shared.'));
|
||||
}
|
||||
|
||||
if (! $this->sharers->isConnected($platform)) {
|
||||
throw new SharingException(__(':platform is not connected. Connect it under Sharing.', ['platform' => $this->sharers->for($platform)->label()]));
|
||||
}
|
||||
|
||||
PostShare::query()->where('post_id', $post->id)->where('platform', $platform)->whereIn('status', [PostShare::PENDING, PostShare::FAILED])->delete();
|
||||
|
||||
return $this->share(PostShare::query()->create(['post_id' => $post->id, 'platform' => $platform, 'status' => PostShare::PENDING]));
|
||||
}
|
||||
|
||||
/**
|
||||
* How sharing stands for a post, per platform, for the manager.
|
||||
*
|
||||
* @return list<array{platform: string, label: string, connected: bool, preview: string, last: ?array{status: string, shared_at: ?string, url: ?string, error: ?string, dry_run: bool}}>
|
||||
*/
|
||||
public function overview(Post $post): array
|
||||
{
|
||||
$shares = PostShare::query()->where('post_id', $post->id)->orderByDesc('id')->get();
|
||||
$overview = [];
|
||||
|
||||
foreach ($this->sharers->names() as $name) {
|
||||
$sharer = $this->sharers->for($name);
|
||||
$last = $shares->first(fn (PostShare $share) => $share->platform === $name && $share->status !== PostShare::PENDING);
|
||||
|
||||
$overview[] = [
|
||||
'platform' => $name,
|
||||
'label' => $sharer->label(),
|
||||
'connected' => $sharer->connection() !== null,
|
||||
'preview' => ShareText::for($post, $sharer->maxLength()),
|
||||
'last' => $last instanceof PostShare ? [
|
||||
'status' => $last->status,
|
||||
'shared_at' => $last->shared_at?->toIso8601String(),
|
||||
'url' => $last->external_url,
|
||||
'error' => $last->error,
|
||||
'dry_run' => (bool) $last->dry_run,
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
|
||||
return $overview;
|
||||
}
|
||||
|
||||
private function share(PostShare $share): PostShare
|
||||
{
|
||||
// Claim the row: whoever changes it from pending to sharing is the one that posts.
|
||||
$claimed = PostShare::query()->whereKey($share->id)->where('status', PostShare::PENDING)->update(['status' => PostShare::SHARING]);
|
||||
|
||||
if ($claimed !== 1) {
|
||||
return $share->refresh();
|
||||
}
|
||||
|
||||
$post = $share->post;
|
||||
|
||||
try {
|
||||
if (! $post instanceof Post || ! $this->sharers->isConnected($share->platform)) {
|
||||
throw new SharingException(__('This platform is not connected. Connect it under Sharing.'));
|
||||
}
|
||||
|
||||
$sharer = $this->sharers->for($share->platform);
|
||||
$text = ShareText::for($post, $sharer->maxLength());
|
||||
$url = ShareText::url($post, $share->platform);
|
||||
|
||||
if ($url === null) {
|
||||
throw new SharingException(__('The site did not say where its posts live (manager.sharing.post_url).'));
|
||||
}
|
||||
|
||||
$share->update(['text' => $text]);
|
||||
|
||||
if (! self::isLive()) {
|
||||
$share->update(['status' => PostShare::SHARED, 'dry_run' => true, 'shared_at' => now(), 'error' => null]);
|
||||
|
||||
return $share;
|
||||
}
|
||||
|
||||
$posted = $sharer->publish(new ShareContent($text, $url, (string) $post->title, ShareText::description($post)));
|
||||
|
||||
$share->update([
|
||||
'status' => PostShare::SHARED,
|
||||
'external_id' => mb_substr($posted->id, 0, 255),
|
||||
'external_url' => $posted->url,
|
||||
'shared_at' => now(),
|
||||
'error' => null,
|
||||
]);
|
||||
} catch (SharingException $e) {
|
||||
$share->update(['status' => PostShare::FAILED, 'error' => mb_substr($e->getMessage(), 0, 500)]);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
$share->update(['status' => PostShare::FAILED, 'error' => __('Something went wrong on this site while sharing. It is in the log.')]);
|
||||
}
|
||||
|
||||
return $share;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
/** Everything a platform needs to post about one post of the site. */
|
||||
final class ShareContent
|
||||
{
|
||||
/**
|
||||
* @param string $text what the post says, already cut to what the platform takes
|
||||
* @param string $url the address of the post on the site, with `?via=<platform>`
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $text,
|
||||
public readonly string $url,
|
||||
public readonly string $title,
|
||||
public readonly string $description,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Support\Markdown;
|
||||
|
||||
/** What a shared post says and links to. */
|
||||
final class ShareText
|
||||
{
|
||||
/**
|
||||
* The address of the post on the site, marked so the statistics know which platform a reader came from. Built from
|
||||
* `manager.sharing.post_url` (for example `https://example.test/blog/{slug}`); null when the site did not say where posts live.
|
||||
*/
|
||||
public static function url(Post $post, string $platform): ?string
|
||||
{
|
||||
$pattern = (string) config('manager.sharing.post_url');
|
||||
|
||||
if ($pattern === '' || ! str_contains($pattern, '{slug}')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$url = str_replace('{slug}', rawurlencode((string) $post->slug), $pattern);
|
||||
|
||||
return $url.(str_contains($url, '?') ? '&' : '?').'via='.rawurlencode($platform);
|
||||
}
|
||||
|
||||
public static function description(Post $post): string
|
||||
{
|
||||
$excerpt = trim((string) $post->excerpt);
|
||||
|
||||
return $excerpt !== '' ? $excerpt : Str::limit(Markdown::toPlainText((string) $post->body), 160);
|
||||
}
|
||||
|
||||
/** The words as they are posted, cut to what the platform takes. */
|
||||
public static function for(Post $post, int $limit): string
|
||||
{
|
||||
return Str::limit(self::description($post), max(1, $limit));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
/** What a platform answered after a post: its id for it and, when it says, where to see it. */
|
||||
final class SharedPost
|
||||
{
|
||||
public function __construct(public readonly string $id, public readonly ?string $url = null) {}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
use IriksIT\Manager\Contracts\Sharer;
|
||||
|
||||
/** Which code posts on which platform: `manager.sharing.platforms` (name => class of a `Sharer`). */
|
||||
final class Sharers
|
||||
{
|
||||
/** @return list<string> the names of the platforms, as the routes and the database know them */
|
||||
public function names(): array
|
||||
{
|
||||
return array_values(array_filter(array_keys((array) config('manager.sharing.platforms', [])), fn ($name) => is_string($name) && preg_match('/^[a-z][a-z0-9_]{0,19}$/', $name) === 1));
|
||||
}
|
||||
|
||||
public function has(string $name): bool
|
||||
{
|
||||
return in_array($name, $this->names(), true);
|
||||
}
|
||||
|
||||
public function for(string $name): Sharer
|
||||
{
|
||||
$class = config("manager.sharing.platforms.{$name}");
|
||||
|
||||
abort_unless($this->has($name) && is_string($class) && is_subclass_of($class, Sharer::class), 404);
|
||||
|
||||
return app($class);
|
||||
}
|
||||
|
||||
/** The owner has connected this platform. */
|
||||
public function isConnected(string $name): bool
|
||||
{
|
||||
return $this->has($name) && $this->for($name)->connection() !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support\Sharing;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Something a platform said or did that the owner can read and act on. Never holds a token. */
|
||||
class SharingException extends RuntimeException {}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\ManagerServiceProvider;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
|
||||
/** What the first page of the screens needs to know: who, what they may do, the menu and the look. */
|
||||
class Shell
|
||||
{
|
||||
public function __construct(private readonly ModuleRegistry $modules, private readonly Themes $themes, private readonly Menu $menu, private readonly LoginChecks $loginChecks) {}
|
||||
|
||||
/** @return array{boot: array<string, mixed>, css: string, scripts: string, styles: string} */
|
||||
public function data(Request $request): array
|
||||
{
|
||||
$user = $request->user();
|
||||
$key = $this->themes->keyFor($user);
|
||||
$theme = $this->themes->all()[$key];
|
||||
$dist = __DIR__.'/../../resources/dist';
|
||||
|
||||
$allowed = $user === null ? [] : array_values(array_filter(
|
||||
[...$this->modules->permissionValues(), ManagerServiceProvider::MANAGE_GROUPS],
|
||||
fn (string $permission) => Gate::forUser($user)->allows($permission),
|
||||
));
|
||||
|
||||
$navigation = $this->menu->for($user, $allowed);
|
||||
$base = '/'.trim((string) config('manager.path'), '/');
|
||||
$primary = $user !== null && method_exists($user, 'managerPrimaryGroup') ? $user->managerPrimaryGroup() : null;
|
||||
// The start screen of the primary group, when this account has it in its menu.
|
||||
$start = $primary?->start !== null && in_array($base.$primary->start, array_column($navigation, 'href'), true) ? $base.$primary->start : null;
|
||||
|
||||
$extensions = array_values(array_filter(
|
||||
(array) config('manager.extensions', []),
|
||||
fn ($url) => is_string($url) && preg_match('#^(/(?!/)|https://)[^\s<>"\'\\\\]*$#', $url) === 1,
|
||||
));
|
||||
|
||||
return [
|
||||
'extensions' => $extensions,
|
||||
'css' => $this->themes->css($theme),
|
||||
'title' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'),
|
||||
'version' => is_file($dist.'/manager.js') ? substr(md5_file($dist.'/manager.js').md5_file($dist.'/manager.css'), 0, 10) : 'dev',
|
||||
'boot' => [
|
||||
'base' => '/'.trim((string) config('manager.path'), '/'),
|
||||
'name' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'),
|
||||
'logo' => $theme['logo'],
|
||||
'locale' => app()->getLocale(),
|
||||
'user' => $user === null ? null : [
|
||||
'name' => (string) ($user->name ?? ''),
|
||||
'email' => (string) ($user->email ?? ''),
|
||||
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
|
||||
'group' => $primary?->name,
|
||||
],
|
||||
'start' => $start,
|
||||
'permissions' => $allowed,
|
||||
'navigation' => $navigation,
|
||||
'extensions' => $user === null ? [] : $extensions,
|
||||
'view' => $this->menu->view($user),
|
||||
'can_switch' => $this->menu->maySwitch($user),
|
||||
'simple_view' => (bool) config('manager.simple_view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial') === 'pending',
|
||||
'tutorial_state' => UserSetting::value($user, 'tutorial'),
|
||||
'tutorial_steps' => $user === null ? [] : $this->modules->tutorial($allowed),
|
||||
'mascot' => '/'.trim((string) config('manager.path'), '/').'/_assets/mascot/',
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'theme' => $key,
|
||||
'can_login' => Route::has(Names::route('login')),
|
||||
'login_fields' => $user === null ? $this->loginChecks->fields() : [],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Creates the tables of a module, but leaves a table alone that is already there.
|
||||
*
|
||||
* A site that had its own manager before has tables with the same job (groups, pages, leads…).
|
||||
* Point `manager.tables` at them and the migrations of the package skip what exists, so the
|
||||
* data stays where it is. `manager:doctor` reports columns the package needs and the table lacks.
|
||||
*/
|
||||
final class Tables
|
||||
{
|
||||
/** @var array<string, list<string>> The columns the package reads and writes, per table (by the name the package uses). */
|
||||
public const COLUMNS = [
|
||||
'audit_logs' => ['id', 'event', 'action', 'summary', 'subject_type', 'subject_id', 'subject_label', 'details', 'user_id', 'user_name', 'email', 'ip', 'user_agent', 'created_at'],
|
||||
'audit_settings' => ['id', 'auto_ban', 'max_failures', 'window_minutes', 'ban_minutes', 'keep_days', 'created_at', 'updated_at'],
|
||||
'block_templates' => ['id', 'resource', 'blocks', 'created_at', 'updated_at'],
|
||||
'bot_hits' => ['id', 'day', 'bot', 'kind', 'path', 'hits'],
|
||||
'group_user' => ['group_id', 'user_id', 'is_primary'],
|
||||
'groups' => ['id', 'name', 'description', 'permissions', 'created_at', 'updated_at', 'start'],
|
||||
'ip_bans' => ['id', 'ip', 'reason', 'automatic', 'whole_site', 'user_id', 'user_name', 'hits', 'last_hit_at', 'expires_at', 'created_at'],
|
||||
'ip_notes' => ['id', 'ip', 'group_name', 'note', 'user_id', 'user_name', 'created_at', 'updated_at'],
|
||||
'lead_blocks' => ['id', 'type', 'value', 'reason', 'expires_at', 'user_id', 'user_name', 'created_at', 'updated_at'],
|
||||
'lead_taps' => ['id', 'day', 'kind', 'path', 'taps'],
|
||||
'leads' => ['id', 'kind', 'folder', 'reasons', 'name', 'phone', 'email', 'prefers', 'about', 'message', 'message_hash', 'answers', 'location', 'subject', 'subject_id', 'page', 'channel', 'source', 'ip', 'opened_at', 'handled_at', 'outcome', 'notes', 'notified_at', 'notify_failed', 'created_at', 'updated_at'],
|
||||
'media' => ['id', 'disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y', 'uploaded_by', 'created_at', 'updated_at'],
|
||||
'page_views' => ['id', 'token', 'visit_id', 'path', 'post_id', 'viewed_at', 'day', 'hour', 'seconds'],
|
||||
'pages' => ['id', 'slug', 'title', 'body', 'is_published', 'created_at', 'updated_at', 'meta_description', 'content', 'blocks'],
|
||||
'post_shares' => ['id', 'post_id', 'platform', 'status', 'text', 'external_id', 'external_url', 'error', 'dry_run', 'shared_at', 'created_at', 'updated_at'],
|
||||
'social_connections' => ['name', 'access_token', 'expires_at', 'refresh_token', 'refresh_token_expires_at', 'account_id', 'account_name', 'details', 'created_at', 'updated_at'],
|
||||
'post_labels' => ['id', 'type', 'name', 'created_at', 'updated_at'],
|
||||
'posts' => ['id', 'title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at', 'created_at', 'updated_at'],
|
||||
'records' => ['id', 'resource', 'data', 'created_at', 'updated_at'],
|
||||
'reviews' => ['id', 'author', 'place', 'rating', 'body', 'is_visible', 'created_at', 'updated_at'],
|
||||
'revisions' => ['id', 'type', 'subject_id', 'user_id', 'user_name', 'data', 'changed', 'created_at'],
|
||||
'settings' => ['id', 'key', 'value', 'is_secret', 'updated_by', 'created_at', 'updated_at'],
|
||||
'storage_files' => ['id', 'path', 'remote_id'],
|
||||
'user_settings' => ['id', 'user_id', 'theme', 'created_at', 'updated_at', 'view', 'locale', 'tutorial'],
|
||||
'work_costs' => ['id', 'fingerprint', 'date', 'name', 'version', 'model', 'usd', 'eur', 'usd_per_eur', 'priced_at', 'created_at', 'updated_at'],
|
||||
'visitor_salts' => ['day', 'salt'],
|
||||
'visits' => ['id', 'visitor_hash', 'started_at', 'last_seen_at', 'day', 'hour', 'weekday', 'entry_path', 'exit_path', 'channel', 'source', 'referrer_host', 'country', 'device', 'browser', 'os', 'page_views', 'seconds'],
|
||||
];
|
||||
|
||||
public static function create(string $table, Closure $callback): bool
|
||||
{
|
||||
if (Schema::hasTable($table)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Schema::create($table, $callback);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Adds a column only when it is not there yet. */
|
||||
public static function addColumn(string $table, string $column, Closure $callback): void
|
||||
{
|
||||
if (Schema::hasTable($table) && ! Schema::hasColumn($table, $column)) {
|
||||
Schema::table($table, fn (Blueprint $blueprint) => $callback($blueprint));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The columns a table lacks for the package, by the name the package uses for it (`groups`, not `site_groups`).
|
||||
* A table the package does not know, or that does not exist, lacks nothing.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function missingColumns(string $name): array
|
||||
{
|
||||
$table = Names::table($name);
|
||||
|
||||
if (! isset(self::COLUMNS[$name]) || ! Schema::hasTable($table)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(self::COLUMNS[$name], fn (string $column) => ! Schema::hasColumn($table, $column)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
|
||||
/**
|
||||
* The looks of the manager. A theme is a name, colours, a radius and fonts, nothing else, and every value is checked
|
||||
* before it ends up in a style block: a theme file can never inject CSS or markup.
|
||||
*
|
||||
* Order: built in (`dark`, `light`), the site's `manager.themes`, then JSON files in `manager.themes_path`.
|
||||
*/
|
||||
class Themes
|
||||
{
|
||||
public const COLORS = ['ink', 'panel', 'panel2', 'line', 'muted', 'text', 'brand', 'brand_alt'];
|
||||
|
||||
private const BUILT_IN = [
|
||||
'dark' => ['label' => 'Dark', 'scheme' => 'dark', 'colors' => [
|
||||
'ink' => '#0a0a12', 'panel' => '#12121d', 'panel2' => '#191927', 'line' => '#26263a',
|
||||
'muted' => '#a3a3b8', 'text' => '#f4f4f8', 'brand' => '#f43676', 'brand_alt' => '#ff6b9d',
|
||||
]],
|
||||
'light' => ['label' => 'Light', 'scheme' => 'light', 'colors' => [
|
||||
'ink' => '#f4f6f8', 'panel' => '#ffffff', 'panel2' => '#eceff3', 'line' => '#d9dee5',
|
||||
'muted' => '#5d6a73', 'text' => '#192c27', 'brand' => '#009ba3', 'brand_alt' => '#007c83',
|
||||
]],
|
||||
];
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
public function all(): array
|
||||
{
|
||||
$themes = self::BUILT_IN;
|
||||
|
||||
foreach ((array) config('manager.themes', []) as $key => $theme) {
|
||||
$themes[(string) $key] = $theme;
|
||||
}
|
||||
|
||||
$path = config('manager.themes_path') ?: (function_exists('resource_path') ? resource_path('manager-themes') : null);
|
||||
|
||||
foreach ($path && is_dir($path) ? glob($path.'/*.json') : [] as $file) {
|
||||
$theme = json_decode((string) file_get_contents($file), true);
|
||||
|
||||
if (is_array($theme)) {
|
||||
$themes[basename($file, '.json')] = $theme;
|
||||
}
|
||||
}
|
||||
|
||||
$clean = [];
|
||||
|
||||
foreach ($themes as $key => $theme) {
|
||||
if (preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', (string) $key) && ($safe = $this->sanitize($key, $theme))) {
|
||||
$clean[$key] = $safe;
|
||||
}
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
/** The key of the theme this account sees: its own choice when allowed, else the site's. */
|
||||
public function keyFor(?object $user): string
|
||||
{
|
||||
$all = $this->all();
|
||||
$default = array_key_exists(config('manager.theme'), $all) ? config('manager.theme') : 'dark';
|
||||
|
||||
if ($user !== null && config('manager.user_themes') && $user->getKey() !== null) {
|
||||
$chosen = UserSetting::query()->where('user_id', $user->getKey())->value('theme');
|
||||
|
||||
if ($chosen !== null && isset($all[$chosen])) {
|
||||
return $chosen;
|
||||
}
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function sanitize(string $key, mixed $theme): ?array
|
||||
{
|
||||
if (! is_array($theme)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$base = self::BUILT_IN[($theme['scheme'] ?? 'dark') === 'light' ? 'light' : 'dark'];
|
||||
$colors = $base['colors'];
|
||||
|
||||
foreach (self::COLORS as $name) {
|
||||
$value = $theme['colors'][$name] ?? null;
|
||||
|
||||
if (is_string($value) && preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value)) {
|
||||
$colors[$name] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$radius = $theme['radius'] ?? '0.5rem';
|
||||
$font = $theme['font'] ?? null;
|
||||
$display = $theme['font_display'] ?? null;
|
||||
$logo = $theme['logo'] ?? null;
|
||||
$name = $theme['name'] ?? null;
|
||||
$label = $theme['label'] ?? ucfirst(str_replace('-', ' ', $key));
|
||||
|
||||
return [
|
||||
'label' => is_string($label) ? mb_substr(strip_tags($label), 0, 60) : $key,
|
||||
'scheme' => $base['scheme'],
|
||||
'colors' => $colors,
|
||||
'radius' => is_string($radius) && preg_match('/^\d{1,2}(\.\d{1,2})?(px|rem)$/', $radius) ? $radius : '0.5rem',
|
||||
'font' => is_string($font) && preg_match('/^[\w ,\'"-]{1,120}$/', $font) ? $font : null,
|
||||
'font_display' => is_string($display) && preg_match('/^[\w ,\'"-]{1,120}$/', $display) ? $display : null,
|
||||
'logo' => is_string($logo) && preg_match('#^(/|https://)[\w\-./%~]{1,300}$#', $logo) ? $logo : null,
|
||||
'name' => is_string($name) ? mb_substr(strip_tags($name), 0, 80) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/** The CSS variables of one theme, ready for a style block (values are already checked). */
|
||||
public function css(array $theme): string
|
||||
{
|
||||
$vars = [];
|
||||
|
||||
foreach ($theme['colors'] as $name => $value) {
|
||||
$vars[] = '--m-'.str_replace('_', '-', $name).':'.$value;
|
||||
}
|
||||
|
||||
$vars[] = '--m-radius:'.$theme['radius'];
|
||||
$theme['font'] && $vars[] = '--m-font:'.$theme['font'];
|
||||
$theme['font_display'] && $vars[] = '--m-font-display:'.$theme['font_display'];
|
||||
$vars[] = 'color-scheme:'.$theme['scheme'];
|
||||
|
||||
return ':root{'.implode(';', $vars).'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Models\Lead;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
|
||||
/**
|
||||
* What the big buttons of the simple start screen say beyond their fixed line: how many requests wait for an answer (and how many of
|
||||
* those are new), how many posts wait to be published, how many visitors came this week. Only for a button the account may see; a
|
||||
* module that is off, or a right the account lacks, gives nothing. By address of the menu item, like the menu itself.
|
||||
*/
|
||||
final class Tiles
|
||||
{
|
||||
public function __construct(private readonly ModuleRegistry $modules, private readonly Numbers $numbers) {}
|
||||
|
||||
/** @return array<string, array{summary?: string, badge?: int}> */
|
||||
public function for(?object $user): array
|
||||
{
|
||||
if ($user === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$can = fn (string $permission): bool => Gate::forUser($user)->allows($permission);
|
||||
$facts = [];
|
||||
|
||||
if ($this->modules->enabled('leads') && $can('leads.view')) {
|
||||
$waiting = Lead::query()->where('folder', Lead::INBOX)->whereNull('handled_at');
|
||||
$new = (clone $waiting)->whereNull('opened_at')->count();
|
||||
$count = $waiting->count();
|
||||
|
||||
$facts[Names::route('leads.index')] = [
|
||||
'summary' => $count === 0
|
||||
? __('Nothing is waiting for an answer.')
|
||||
: trans_choice('{1} :count is waiting for an answer|[2,*] :count are waiting for an answer', $count, ['count' => $count]).($new > 0 ? ', '.__(':new of them new', ['new' => $new]) : '').'.',
|
||||
'badge' => $new,
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->modules->enabled('posts') && $can('posts.view')) {
|
||||
$drafts = Post::query()->whereNull('published_at')->count();
|
||||
|
||||
if ($drafts > 0) {
|
||||
$facts[Names::route('posts.index')] = ['summary' => trans_choice('{1} :count post is waiting for you.|[2,*] :count posts are waiting for you.', $drafts, ['count' => $drafts])];
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->modules->enabled('numbers') && $can('numbers.view')) {
|
||||
$visitors = $this->numbers->visitorsThisWeek();
|
||||
|
||||
if ($visitors > 0) {
|
||||
$facts[Names::route('numbers.index')] = ['summary' => trans_choice('{1} :count visitor in the last 7 days.|[2,*] :count visitors in the last 7 days.', $visitors, ['count' => $visitors])];
|
||||
}
|
||||
}
|
||||
|
||||
return $facts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
/**
|
||||
* What the statistics want to know from a browser's User-Agent line: is it a
|
||||
* person, and roughly which device, browser and system. Rough on purpose; the
|
||||
* line itself is never stored.
|
||||
*/
|
||||
final class UserAgent
|
||||
{
|
||||
private const BOTS = '/bot|crawl|spider|slurp|preview|headless|lighthouse|pagespeed|pingdom|uptime|monitor|scan'
|
||||
.'|fetch|curl|wget|python|java\/|go-http|okhttp|axios|node|php|ruby|perl|libwww|httpclient|postman|insomnia'
|
||||
.'|facebookexternalhit|whatsapp|telegram|slack|discord|embedly|feed|validator|archive|phantom|selenium|puppeteer|playwright'
|
||||
// Programs that say none of the words above: AI assistants, Google's other fetchers, scanners, monitors, feed readers.
|
||||
.'|chatgpt-user|claude-user|claude-web|anthropic-ai|perplexity-user|cohere|mistralai|externalagent|externalfetcher'
|
||||
.'|googleother|google-extended|google-cloudvertex|inspectiontool|mediapartners|apis-google|sogou|qwantify|screaming frog'
|
||||
.'|censys|shodan|expanse|zgrab|masscan|nmap|nuclei|nikto|sqlmap|wpscan|buster|internetmeasurement|l9explore|l9tcpid|leakix'
|
||||
.'|gtmetrix|site24x7|statuscake|better uptime|betterstack|zabbix|nagios|check_http|datadog|newrelic'
|
||||
.'|inoreader|newsblur|miniflux|freshrss|tiny tiny rss|mastodon|pleroma|akkoma|misskey|bluesky|iframely'
|
||||
.'|guzzle|scrapy|aiohttp|httpx|undici|faraday|apache-httpclient/i';
|
||||
|
||||
public function __construct(private readonly string $line) {}
|
||||
|
||||
/** No browser line at all, or one of a program: not a visitor. */
|
||||
public function isBot(): bool
|
||||
{
|
||||
return trim($this->line) === '' || preg_match(self::BOTS, $this->line) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The programs the statistics know by name, as pattern => [name, kind]. The
|
||||
* first one that fits wins, so a longer name stands before the one it holds
|
||||
* ("Applebot-Extended" before "Applebot").
|
||||
*
|
||||
* Kinds: search (search engine), ai (collects for or answers through an AI),
|
||||
* seo (marketing tools), social (the preview of a shared link), monitor, feed,
|
||||
* archive, scanner (looks for weak spots), script (a program or library).
|
||||
*/
|
||||
private const KNOWN_BOTS = [
|
||||
'/GPTBot/i' => ['GPTBot', 'ai'],
|
||||
'/ChatGPT-User/i' => ['ChatGPT', 'ai'],
|
||||
'/OAI-SearchBot/i' => ['OpenAI search', 'ai'],
|
||||
'/Claude-SearchBot/i' => ['Claude search', 'ai'],
|
||||
'/Claude-User/i' => ['Claude', 'ai'],
|
||||
'/ClaudeBot|anthropic-ai|claude-web/i' => ['ClaudeBot', 'ai'],
|
||||
'/Perplexity-User/i' => ['Perplexity', 'ai'],
|
||||
'/PerplexityBot/i' => ['PerplexityBot', 'ai'],
|
||||
'/Google-Extended|GoogleOther|Google-CloudVertexBot/i' => ['Google (AI and other)', 'ai'],
|
||||
'/Applebot-Extended/i' => ['Applebot-Extended', 'ai'],
|
||||
'/meta-externalagent|meta-externalfetcher/i' => ['Meta AI', 'ai'],
|
||||
'/Bytespider/i' => ['Bytespider', 'ai'],
|
||||
'/Amazonbot/i' => ['Amazonbot', 'ai'],
|
||||
'/CCBot/i' => ['Common Crawl', 'ai'],
|
||||
'/cohere-ai|cohere-training/i' => ['Cohere', 'ai'],
|
||||
'/MistralAI/i' => ['Mistral', 'ai'],
|
||||
'/DuckAssistBot/i' => ['DuckAssist', 'ai'],
|
||||
'/YouBot/i' => ['YouBot', 'ai'],
|
||||
'/Diffbot/i' => ['Diffbot', 'ai'],
|
||||
'/ImagesiftBot/i' => ['ImagesiftBot', 'ai'],
|
||||
'/Timpibot/i' => ['Timpibot', 'ai'],
|
||||
|
||||
'/Googlebot|Google-InspectionTool|Storebot-Google|AdsBot-Google|Mediapartners-Google|APIs-Google/i' => ['Googlebot', 'search'],
|
||||
'/bingbot|BingPreview|adidxbot|msnbot/i' => ['Bingbot', 'search'],
|
||||
'/DuckDuckBot|DuckDuckGo/i' => ['DuckDuckBot', 'search'],
|
||||
'/YandexBot|YandexImages|Yandex/i' => ['YandexBot', 'search'],
|
||||
'/Baiduspider/i' => ['Baiduspider', 'search'],
|
||||
'/Applebot/i' => ['Applebot', 'search'],
|
||||
'/Slurp/i' => ['Yahoo', 'search'],
|
||||
'/Qwantbot|Qwantify/i' => ['Qwant', 'search'],
|
||||
'/SeznamBot/i' => ['SeznamBot', 'search'],
|
||||
'/PetalBot/i' => ['PetalBot', 'search'],
|
||||
'/Sogou/i' => ['Sogou', 'search'],
|
||||
'/MojeekBot/i' => ['Mojeek', 'search'],
|
||||
'/Bravebot/i' => ['Brave', 'search'],
|
||||
'/Kagibot/i' => ['Kagi', 'search'],
|
||||
|
||||
'/AhrefsBot|AhrefsSiteAudit/i' => ['AhrefsBot', 'seo'],
|
||||
'/SemrushBot|SiteAuditBot|SplitSignalBot/i' => ['SemrushBot', 'seo'],
|
||||
'/MJ12bot/i' => ['Majestic', 'seo'],
|
||||
'/DotBot|rogerbot/i' => ['Moz', 'seo'],
|
||||
'/DataForSeoBot/i' => ['DataForSEO', 'seo'],
|
||||
'/BLEXBot/i' => ['BLEXBot', 'seo'],
|
||||
'/SerpstatBot/i' => ['Serpstat', 'seo'],
|
||||
'/Barkrowler/i' => ['Barkrowler', 'seo'],
|
||||
'/Screaming Frog/i' => ['Screaming Frog', 'seo'],
|
||||
'/SEOkicks|seobility|Sistrix|linkdexbot/i' => ['Other SEO tool', 'seo'],
|
||||
|
||||
'/facebookexternalhit|Facebot|facebookcatalog/i' => ['Facebook', 'social'],
|
||||
'/LinkedInBot/i' => ['LinkedIn', 'social'],
|
||||
'/Twitterbot/i' => ['X', 'social'],
|
||||
'/WhatsApp/i' => ['WhatsApp', 'social'],
|
||||
'/TelegramBot/i' => ['Telegram', 'social'],
|
||||
'/Slackbot|Slack-ImgProxy/i' => ['Slack', 'social'],
|
||||
'/Discordbot/i' => ['Discord', 'social'],
|
||||
'/Pinterestbot|Pinterest\\/0/i' => ['Pinterest', 'social'],
|
||||
'/redditbot/i' => ['Reddit', 'social'],
|
||||
'/Mastodon|Pleroma|Akkoma|Misskey/i' => ['Mastodon and the fediverse', 'social'],
|
||||
'/Bluesky/i' => ['Bluesky', 'social'],
|
||||
'/SkypeUriPreview|MicrosoftPreview/i' => ['Microsoft link preview', 'social'],
|
||||
'/Embedly|Iframely/i' => ['Embed service', 'social'],
|
||||
|
||||
'/UptimeRobot/i' => ['UptimeRobot', 'monitor'],
|
||||
'/Uptime-Kuma/i' => ['Uptime Kuma', 'monitor'],
|
||||
'/Pingdom/i' => ['Pingdom', 'monitor'],
|
||||
'/StatusCake/i' => ['StatusCake', 'monitor'],
|
||||
'/Better Uptime|BetterStack/i' => ['Better Stack', 'monitor'],
|
||||
'/Site24x7/i' => ['Site24x7', 'monitor'],
|
||||
'/Lighthouse|PageSpeed|GTmetrix/i' => ['Speed test', 'monitor'],
|
||||
'/Cloudflare/i' => ['Cloudflare', 'monitor'],
|
||||
'/Zabbix|Nagios|check_http|Datadog|NewRelic/i' => ['Other monitoring', 'monitor'],
|
||||
|
||||
'/Feedly|Feedbin|Inoreader|NewsBlur|Miniflux|FreshRSS|Tiny Tiny RSS|FeedFetcher/i' => ['Feed reader', 'feed'],
|
||||
'/archive\.org_bot|ia_archiver|Wayback/i' => ['Internet Archive', 'archive'],
|
||||
|
||||
'/CensysInspect/i' => ['Censys', 'scanner'],
|
||||
'/Shodan/i' => ['Shodan', 'scanner'],
|
||||
'/Expanse|Palo Alto/i' => ['Palo Alto Expanse', 'scanner'],
|
||||
'/InternetMeasurement/i' => ['InternetMeasurement', 'scanner'],
|
||||
'/l9explore|l9tcpid|LeakIX/i' => ['LeakIX', 'scanner'],
|
||||
'/zgrab|masscan|Nmap|Nuclei|Nikto|sqlmap|WPScan|dirbuster|gobuster/i' => ['Scanning tool', 'scanner'],
|
||||
|
||||
'/HeadlessChrome|Puppeteer|Playwright|Selenium|PhantomJS/i' => ['Headless browser', 'script'],
|
||||
'/curl/i' => ['curl', 'script'],
|
||||
'/Wget/i' => ['Wget', 'script'],
|
||||
'/python|aiohttp|httpx|scrapy/i' => ['Python', 'script'],
|
||||
'/Go-http-client/i' => ['Go', 'script'],
|
||||
'/okhttp|Java\/|Apache-HttpClient/i' => ['Java', 'script'],
|
||||
'/axios|node-fetch|undici|node/i' => ['Node.js', 'script'],
|
||||
'/Guzzle|PHP/i' => ['PHP', 'script'],
|
||||
'/Ruby|Faraday/i' => ['Ruby', 'script'],
|
||||
'/libwww-perl|Perl/i' => ['Perl', 'script'],
|
||||
'/Postman|Insomnia/i' => ['API client', 'script'],
|
||||
];
|
||||
|
||||
/** For a program that is not in the list: the word in its line that names it. */
|
||||
private const BOT_WORD = '/[A-Za-z0-9][A-Za-z0-9._-]*(?:bot|crawler|crawl|spider|scan|fetch|monitor|preview|archive|validator)[A-Za-z0-9._-]*/i';
|
||||
|
||||
/**
|
||||
* Which program this is, or null for a person. A program that is not known
|
||||
* by name is called by the one word of its line that names it ("FooBot"),
|
||||
* never by the line; without such a word it is `null` as a name, for the
|
||||
* caller to file under "other".
|
||||
*
|
||||
* @return array{name: string|null, kind: string}|null
|
||||
*/
|
||||
public function bot(): ?array
|
||||
{
|
||||
if (! $this->isBot()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (self::KNOWN_BOTS as $pattern => [$name, $kind]) {
|
||||
if (preg_match($pattern, $this->line) === 1) {
|
||||
return ['name' => $name, 'kind' => $kind];
|
||||
}
|
||||
}
|
||||
|
||||
$word = preg_match(self::BOT_WORD, $this->line, $match) === 1 ? substr($match[0], 0, 40) : null;
|
||||
|
||||
return ['name' => $word, 'kind' => 'other'];
|
||||
}
|
||||
|
||||
public function device(): string
|
||||
{
|
||||
if (preg_match('/iPad|Tablet|PlayBook|Silk/i', $this->line) === 1
|
||||
|| (str_contains($this->line, 'Android') && ! str_contains($this->line, 'Mobile'))) {
|
||||
return 'tablet';
|
||||
}
|
||||
|
||||
return preg_match('/Mobi|iPhone|iPod|Android/i', $this->line) === 1 ? 'mobile' : 'desktop';
|
||||
}
|
||||
|
||||
public function browser(): string
|
||||
{
|
||||
// Order matters: nearly every browser also says "Chrome" and "Safari".
|
||||
$browsers = [
|
||||
'Edge' => '/Edg(e|A|iOS)?\//',
|
||||
'Opera' => '/OPR\/|Opera/',
|
||||
'Samsung Internet' => '/SamsungBrowser\//',
|
||||
'Vivaldi' => '/Vivaldi\//',
|
||||
'Firefox' => '/Firefox\/|FxiOS\//',
|
||||
'Chrome' => '/Chrome\/|CriOS\//',
|
||||
'Safari' => '/Safari\//',
|
||||
];
|
||||
|
||||
foreach ($browsers as $name => $pattern) {
|
||||
if (preg_match($pattern, $this->line) === 1) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
return 'Other';
|
||||
}
|
||||
|
||||
public function os(): string
|
||||
{
|
||||
$systems = [
|
||||
'iOS' => '/iPhone|iPad|iPod/',
|
||||
'Android' => '/Android/',
|
||||
'Windows' => '/Windows/',
|
||||
'macOS' => '/Mac OS X|Macintosh/',
|
||||
'ChromeOS' => '/CrOS/',
|
||||
'Linux' => '/Linux|X11/',
|
||||
];
|
||||
|
||||
foreach ($systems as $name => $pattern) {
|
||||
if (preg_match($pattern, $this->line) === 1) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
return 'Other';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user