]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CleanupImagesCommand.php
Notifications: Switched testing from string to reference levels
[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->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 . ' images 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 . ' images deleted');
58         return 0;
59     }
60
61     protected function showDeletedImages($paths): void
62     {
63         if ($this->getOutput()->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
64             return;
65         }
66
67         if (count($paths) > 0) {
68             $this->line('Images to delete:');
69         }
70
71         foreach ($paths as $path) {
72             $this->line($path);
73         }
74     }
75 }