]> BookStack Code Mirror - bookstack/blob - app/Exports/ImportRepo.php
ZIP Imports: Added listing, show view, delete, activity
[bookstack] / app / Exports / ImportRepo.php
1 <?php
2
3 namespace BookStack\Exports;
4
5 use BookStack\Exceptions\ZipValidationException;
6 use BookStack\Exports\ZipExports\ZipExportReader;
7 use BookStack\Exports\ZipExports\ZipExportValidator;
8 use BookStack\Uploads\FileStorage;
9 use Illuminate\Database\Eloquent\Collection;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12 class ImportRepo
13 {
14     public function __construct(
15         protected FileStorage $storage,
16     ) {
17     }
18
19     /**
20      * @return Collection<Import>
21      */
22     public function getVisibleImports(): Collection
23     {
24         $query = Import::query();
25
26         if (!userCan('settings-manage')) {
27             $query->where('created_by', user()->id);
28         }
29
30         return $query->get();
31     }
32
33     public function findVisible(int $id): Import
34     {
35         $query = Import::query();
36
37         if (!userCan('settings-manage')) {
38             $query->where('created_by', user()->id);
39         }
40
41         return $query->findOrFail($id);
42     }
43
44     public function storeFromUpload(UploadedFile $file): Import
45     {
46         $zipPath = $file->getRealPath();
47
48         $errors = (new ZipExportValidator($zipPath))->validate();
49         if ($errors) {
50             throw new ZipValidationException($errors);
51         }
52
53         $zipEntityInfo = (new ZipExportReader($zipPath))->getEntityInfo();
54         $import = new Import();
55         $import->name = $zipEntityInfo['name'];
56         $import->book_count = $zipEntityInfo['book_count'];
57         $import->chapter_count = $zipEntityInfo['chapter_count'];
58         $import->page_count = $zipEntityInfo['page_count'];
59         $import->created_by = user()->id;
60         $import->size = filesize($zipPath);
61
62         $path = $this->storage->uploadFile(
63             $file,
64             'uploads/files/imports/',
65             '',
66             'zip'
67         );
68
69         $import->path = $path;
70         $import->save();
71
72         return $import;
73     }
74
75     public function deleteImport(Import $import): void
76     {
77         $this->storage->delete($import->path);
78         $import->delete();
79     }
80 }