Add a history of posts and pages with restore
This commit is contained in:
1 parent
eb37a7c6fb
commit
6fdb02040b
20 files changed
+482
-8
No files matched your search
@@ -26,7 +26,7 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
|
||||
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
|
||||
// A config that was published before resources existed does not list their module.
|
||||
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class])),
|
||||
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class])),
|
||||
$app['config']->get('manager.modules', []),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Models;
|
||||
|
||||
/** An earlier state of a post, a page or another record that keeps a history (module `revisions`). */
|
||||
class Revision extends Model
|
||||
{
|
||||
/** Only `created_at`, set when the state is kept. */
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['data' => 'array', 'changed' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,7 @@ class PagesController
|
||||
abort_if($definition === null && $page === null, 404);
|
||||
|
||||
return [
|
||||
'id' => $page?->id,
|
||||
'slug' => $slug,
|
||||
'title' => $page->title ?? $definition['title'],
|
||||
'meta_description' => $page->meta_description ?? '',
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Revisions;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
use IriksIT\Manager\Models\Revision;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Revisions;
|
||||
|
||||
class RevisionController
|
||||
{
|
||||
public function index(string $type, string $id): JsonResponse
|
||||
{
|
||||
[$config, $model] = $this->find($type, $id, 'view');
|
||||
|
||||
$revisions = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->orderByDesc('id')->limit(100)->get();
|
||||
|
||||
return response()->json([
|
||||
'revisions' => $revisions->map(fn (Revision $revision, int $position) => [
|
||||
'id' => $revision->id,
|
||||
'created_at' => $revision->created_at,
|
||||
'user' => $revision->user_name,
|
||||
'changed' => $revision->changed ?? [],
|
||||
'current' => $position === 0,
|
||||
// What the changed attributes were then, shortened: enough to see what an old version said.
|
||||
'values' => collect($revision->changed ?? [])->mapWithKeys(fn (string $key) => [$key => $this->shorten($revision->data[$key] ?? null)])->all(),
|
||||
])->values(),
|
||||
'can_restore' => Gate::allows('revisions.restore') && Gate::allows($config['restore']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function restore(string $type, string $id, string $revision): JsonResponse
|
||||
{
|
||||
[$config, $model] = $this->find($type, $id, 'restore');
|
||||
$revision = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->whereKey($revision)->firstOrFail();
|
||||
|
||||
// A post that is on the site is only changed by someone who may publish.
|
||||
abort_if($model instanceof Post && $model->isPublished() && Gate::denies('posts.publish'), 403);
|
||||
|
||||
app(AuditTrail::class)->about($model);
|
||||
Revisions::restore($model, $revision, $config);
|
||||
|
||||
return response()->json(['restored' => true]);
|
||||
}
|
||||
|
||||
/** @return array{0: array{model: class-string<Model>, view: string, restore: string, except: list<string>}, 1: Model} */
|
||||
private function find(string $type, string $id, string $ability): array
|
||||
{
|
||||
$config = Revisions::types()[$type] ?? null;
|
||||
abort_if($config === null, 404);
|
||||
Gate::authorize($config[$ability]);
|
||||
|
||||
return [$config, $config['model']::query()->findOrFail($id)];
|
||||
}
|
||||
|
||||
private function shorten(mixed $value): mixed
|
||||
{
|
||||
$text = is_scalar($value) || $value === null ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
return mb_strlen($text) > 300 ? mb_substr($text, 0, 300).'…' : $text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Revisions;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
use IriksIT\Manager\Support\Revisions;
|
||||
|
||||
/** The history of posts and pages (and of what a site adds): see an earlier state and put it back. */
|
||||
class RevisionsModule extends BaseModule
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'revisions';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'History';
|
||||
}
|
||||
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function tables(): array
|
||||
{
|
||||
return ['revisions'];
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
new Permission('revisions.view', 'See the history of posts and pages', 'History'),
|
||||
new Permission('revisions.restore', 'Put an earlier version of a post or page back', 'History', needs: ['revisions.view']),
|
||||
];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return ['revisions.restore' => ['Put an earlier version back']];
|
||||
}
|
||||
|
||||
public function views(): array
|
||||
{
|
||||
return ['revisions.index' => 'Opened the history of a text'];
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Revisions::listen();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create(Names::table('revisions'), function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('type', 40);
|
||||
$table->unsignedBigInteger('subject_id');
|
||||
// Who saved it: no foreign key, so the history stays when an account is removed.
|
||||
$table->unsignedBigInteger('user_id')->nullable();
|
||||
$table->string('user_name')->nullable();
|
||||
$table->json('data');
|
||||
$table->json('changed')->nullable();
|
||||
$table->dateTime('created_at');
|
||||
|
||||
$table->index(['type', 'subject_id', 'id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists(Names::table('revisions'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Revisions\RevisionController;
|
||||
|
||||
// `{type}` is a key of Support\Revisions::types(); the controller checks the permissions of that type too.
|
||||
Route::middleware('can:revisions.view')->prefix('/revisions/{type}/{id}')->where(['type' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+', 'revision' => '[0-9]+'])->group(function () {
|
||||
Route::get('/', [RevisionController::class, 'index'])->name('revisions.index');
|
||||
Route::post('/{revision}/restore', [RevisionController::class, 'restore'])->name('revisions.restore')->middleware('can:revisions.restore');
|
||||
});
|
||||
@@ -0,0 +1,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)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user