]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CleanupImagesCommand.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Console / Commands / CleanupImagesCommand.php
1 <?php
2
3 namespace BookStack\Console\Commands;
4
5 use BookStack\Uploads\ImageService;
6 use Illuminate\Console\Command;
7 use Symfony\Component\Console\Output\OutputInterface;
8
9 class CleanupImagesCommand extends Command
10 {
11     /**
12      * The name and signature of the console command.
13      *
14      * @var string
15      */
16     protected $signature = 'bookstack:cleanup-images
17                             {--a|all : Also delete images that are only used in old revisions}
18                             {--f|force : Actually run the deletions, Defaults to a dry-run}
19                             ';
20
21     /**
22      * The console command description.
23      *
24      * @var string
25      */
26     protected $description = 'Cleanup images and drawings';
27
28     /**
29      * Execute the console command.
30      */
31     public function handle(ImageService $imageService): int
32     {
33         $checkRevisions = !$this->option('all');
34         $dryRun = !$this->option('force');
35
36         if (!$dryRun) {
37             $this->warn("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\n");
38             $proceed = !$this->input->isInteractive() || $this->confirm("Are you sure you want to proceed?");
39             if (!$proceed) {
40                 return 0;
41             }
42         }
43
44         $deleted = $imageService->deleteUnusedImages($checkRevisions, $dryRun);
45         $deleteCount = count($deleted);
46
47         if ($dryRun) {
48             $this->comment('Dry run, no images have been deleted');
49             $this->comment($deleteCount . ' image(s) found that would have been deleted');
50             $this->showDeletedImages($deleted);
51             $this->comment('Run with -f or --force to perform deletions');
52
53             return 0;
54         }
55
56         $this->showDeletedImages($deleted);
57         $this->comment("{$deleteCount} image(s) deleted");
58
59         return 0;
60     }
61
62     protected function showDeletedImages($paths): void
63     {
64         if ($this->getOutput()->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
65             return;
66         }
67
68         if (count($paths) > 0) {
69             $this->line('Image(s) to delete:');
70         }
71
72         foreach ($paths as $path) {
73             $this->line($path);
74         }
75     }
76 }