]> BookStack Code Mirror - hacks/blob - content/prune-revisions-command/functions.php
Added prune revisions command hack
[hacks] / content / prune-revisions-command / functions.php
1 <?php
2
3 use BookStack\Entities\Models\Page;
4 use BookStack\Facades\Theme;
5 use Illuminate\Console\Command;
6 use Illuminate\Database\Eloquent\Builder;
7
8 // Define the command we want to add to BookStack
9 class PruneRevisionsCommand extends Command
10 {
11     // Specify how the command should be called, and the description that'll show for it
12     protected $signature = 'bookstack:prune-revisions {bookslug} {pageslug}';
13     protected $description = 'Remove revisions without changelog and reset numbers for a specific page';
14
15     // Define the function that'll be called when the command is performed
16     public function handle(): int
17     {
18         $pageSlug = $this->argument('pageslug');
19         $bookSlug = $this->argument('bookslug');
20
21         // Find the provided page using slugs
22         $page = Page::query()->whereHas('book', function (Builder $query) use ($bookSlug) {
23             $query->where('slug', '=', $bookSlug);
24         })->where('slug', '=', $pageSlug)->first();
25
26         // Return as an error if the page is not found
27         if (!$page) {
28             $this->error("Page of slugs {$bookSlug}:{$pageSlug} not found");
29             return 1;
30         }
31
32         // Delete revisions without changelog, except if it's the current revision
33         $currentRevision = $page->currentRevision()->first();
34         $deleteCount = $page->allRevisions()
35             ->where('type', '=', 'version')
36             ->where('summary', '=', '')
37             ->where('id', '!=', $currentRevision->id)
38             ->delete();
39
40         // Reset numbers on the revisions
41         $revisions = $page->allRevisions()->where('type', '=', 'version')
42             ->orderBy('created_at', 'asc')
43             ->get()
44             ->all();
45         foreach ($revisions as $index => $revision) {
46             $revision->revision_number = $index + 1;
47             $revision->save();
48         }
49
50         // Update page revision count
51         $page->revision_count = count($revisions);
52         $page->save();
53
54         $this->line("Revisions pruned and re-numbered for page [{$page->name}] with {$deleteCount} revisions deleted");
55
56         return 0;
57     }
58 }
59
60 // Register our command via the theme system
61 Theme::registerCommand(new PruneRevisionsCommand());