3 namespace BookStack\Exports;
5 use BookStack\Exceptions\FileUploadException;
6 use BookStack\Exceptions\ZipExportException;
7 use BookStack\Exceptions\ZipValidationException;
8 use BookStack\Exports\ZipExports\Models\ZipExportBook;
9 use BookStack\Exports\ZipExports\Models\ZipExportChapter;
10 use BookStack\Exports\ZipExports\Models\ZipExportPage;
11 use BookStack\Exports\ZipExports\ZipExportReader;
12 use BookStack\Exports\ZipExports\ZipExportValidator;
13 use BookStack\Uploads\FileStorage;
14 use Illuminate\Database\Eloquent\Collection;
15 use Symfony\Component\HttpFoundation\File\UploadedFile;
19 public function __construct(
20 protected FileStorage $storage,
25 * @return Collection<Import>
27 public function getVisibleImports(): Collection
29 $query = Import::query();
31 if (!userCan('settings-manage')) {
32 $query->where('created_by', user()->id);
38 public function findVisible(int $id): Import
40 $query = Import::query();
42 if (!userCan('settings-manage')) {
43 $query->where('created_by', user()->id);
46 return $query->findOrFail($id);
50 * @throws FileUploadException
51 * @throws ZipValidationException
52 * @throws ZipExportException
54 public function storeFromUpload(UploadedFile $file): Import
56 $zipPath = $file->getRealPath();
58 $errors = (new ZipExportValidator($zipPath))->validate();
60 throw new ZipValidationException($errors);
63 $reader = new ZipExportReader($zipPath);
64 $exportModel = $reader->decodeDataToExportModel();
66 $import = new Import();
67 $import->type = match (get_class($exportModel)) {
68 ZipExportPage::class => 'page',
69 ZipExportChapter::class => 'chapter',
70 ZipExportBook::class => 'book',
73 $import->name = $exportModel->name;
74 $import->created_by = user()->id;
75 $import->size = filesize($zipPath);
77 $exportModel->metadataOnly();
78 $import->metadata = json_encode($exportModel);
80 $path = $this->storage->uploadFile(
82 'uploads/files/imports/',
87 $import->path = $path;
93 public function runImport(Import $import, ?string $parent = null)
95 // TODO - Download import zip (if needed)
96 // TODO - Validate zip file again
97 // TODO - Check permissions before (create for main item, create for children, create for related items [image, attachments])
100 public function deleteImport(Import $import): void
102 $this->storage->delete($import->path);