]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CleanupImages.php
2399e1cbb341460a2af5946648b9d57e344612b2
[bookstack] / app / Console / Commands / CleanupImages.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 CleanupImages 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     protected $imageService;
29
30     /**
31      * Create a new command instance.
32      *
33      * @param \BookStack\Uploads\ImageService $imageService
34      */
35     public function __construct(ImageService $imageService)
36     {
37         $this->imageService = $imageService;
38         parent::__construct();
39     }
40
41     /**
42      * Execute the console command.
43      *
44      * @return mixed
45      */
46     public function handle()
47     {
48         $checkRevisions = $this->option('all') ? false : true;
49         $dryRun = $this->option('force') ? false : true;
50
51         if (!$dryRun) {
52             $this->warn("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\n");
53             $proceed = $this->confirm("Are you sure you want to proceed?");
54             if (!$proceed) {
55                 return;
56             }
57         }
58
59         $deleted = $this->imageService->deleteUnusedImages($checkRevisions, $dryRun);
60         $deleteCount = count($deleted);
61
62         if ($dryRun) {
63             $this->comment('Dry run, no images have been deleted');
64             $this->comment($deleteCount . ' images found that would have been deleted');
65             $this->showDeletedImages($deleted);
66             $this->comment('Run with -f or --force to perform deletions');
67
68             return;
69         }
70
71         $this->showDeletedImages($deleted);
72         $this->comment($deleteCount . ' images deleted');
73     }
74
75     protected function showDeletedImages($paths)
76     {
77         if ($this->getOutput()->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
78             return;
79         }
80         if (count($paths) > 0) {
81             $this->line('Images to delete:');
82         }
83         foreach ($paths as $path) {
84             $this->line($path);
85         }
86     }
87 }